Library contents

C++ std::strcspn

Find the first carriage return or line feed and terminate a writable code buffer there.

A simple example

std::strcspn

  1. Start with A followed by a newline
  2. Do this Count up to the first line ending
  3. Result 1
Only A appears before the newline. Its length gives the position where the ending begins.

Syntax

C++ syntax
std::strcspn(code, "\r\n")
Run these examples in C++

Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.

c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson

Remove the line ending from a delivery code

A terminal appends padding or a line ending to the final field it exports. Remove the trailing characters before comparing or displaying the value, while retaining the beginning of the field.

From the programchar code[] = "AB-17\r\n"
ResultAB-17
lesson.cpp
#include <cstring>
#include <cstdio>

int main() {
    char code[] = "AB-17\r\n";
    code[std::strcspn(code, "\r\n")] = '\0';
    std::puts(code);
    return 0;
}
Output
AB-17

The carriage return comes first here. Replacing that byte with a terminator removes the line ending from printed output.

Advertisements

Read a Windows label row

A desk imports a badge followed by a CRLF pair. The input record ends at the first carriage return or line feed. Which text precedes that boundary?

GivenLAB-5 + CRLF
Worked resultLAB-5

Keep a final row

A meter sends a final label without a terminator. The input record ends at the first carriage return or line feed. Which text precedes that boundary?

GivenDock + end of input
Worked resultDock

What to watch for

Modify a writable array. A string literal must never be edited.

Documentation for std::strcspn