I have a little getline function that works okay unless there's a ctrl+z in the stream. Here's some code:
If I type "abcd^Z" it works. If I type "abc^Z", it doesn't see the eof and puts ascii 26 as the last character. I can check for ascii 26, but that's kludgy. Can somebody suggest something better?Code:#include <stdio.h> #include <string.h> /* return true: the string is empty due to hitting a delimiter right away the string is not empty return false: the string is empty due to eof or a stream error */ int getline( char *string, int size, char delimiter ) { int i = 0; int c; if ( size > 0 ) { // stop reading at size, eof, or a delimiter while ( --size > 0 && ( c = getchar() ) != EOF && ( string[i++] = c ) != delimiter ); // trim the delimiter if it's there and end the string string[i - ( i && string[i - 1] == delimiter )] = '\0'; // clear the stream up to the next delimiter while ( stdin->_cnt > 0 && !ferror( stdin ) && ( c = getchar() ) != EOF && c != delimiter ); } return i != 0; } int main( void ) { char array[5]; while ( 1 ) { int rc = getline( array, 5, '\n' ); printf( "%d: %s\n", rc, array ); } return 0; }



LinkBack URL
About LinkBacks



