C++ std::strcspn
Find the first carriage return or line feed and terminate a writable code buffer there.
A simple example
std::strcspn
- Start with A followed by a newline
- Do this Count up to the first line ending
- Result 1
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
./lessonRemove 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.
#include <cstring>
#include <cstdio>
int main() {
char code[] = "AB-17\r\n";
code[std::strcspn(code, "\r\n")] = '\0';
std::puts(code);
return 0;
}
AB-17
The carriage return comes first here. Replacing that byte with a terminator removes the line ending from printed output.
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?
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?
What to watch for
Modify a writable array. A string literal must never be edited.