Trimming end-of-line characters from a line
To make future examples easy to read,
we'll write a function, named trim_line(),
that receives a line (a character array) as a parameter,
and "removes" the first carriage-return or newline character that it finds.
It's very similar to functions like my_strlen()
that we've written in laboratory work:
// REMOVE ANY TRAILING end-of-line CHARACTERS FROM THE LINE
void trim_line(char line[])
{
int i = 0;
// LOOP UNTIL WE REACH THE END OF line
while(line[i] != '\0') {
// CHECK FOR CARRIAGE-RETURN OR NEWLINE
if( line[i] == '\r' || line[i] == '\n' ) {
line[i] = '\0'; // overwrite with null-byte
break; // leave the loop early
}
i = i+1; // iterate through character array
}
}
|
We note:
- we simply overwrite the unwanted character with the null-byte.
- the function will actually modify the caller's copy of the variable.
- we do not return any value.
CITS2002 Systems Programming, Lecture 7, p7, 12th August 2024.
|