简体   繁体   中英

C read lines from stdin ending by pressing Enter

I'm writing a program for project in C, where I have such kind of input:

  ............xcx............
  .........qeztodlea.........
  .......ecnedivorpuzy.......
  .....bqfjwxqindnrsatrs.....
  ....ucaamadisonoctoieax....
  ...ozkttqdxwltstaivcilex...
  ...ujknnakigzfasxninltxc...
  ..rabxaa...kohce...oelnyd..
  ..rithls...momrl...spayvh..

      honolulu
  oklahomacity
  charleston
  madison
  montgomery
  saltlakecity
  springfield

First set of data is separated from second data set by empty line, I need on one Enter press process it.

If I copy-past this data in terminal window and press Enter and then Ctr+D ( which means end of input ) it works fine, but if to press only Enter I still need to enter data. I can't understand what to change so only on first Enter I'll finish input and proceed to my program? I know that this question sounds stupid, but in my function for reading line I use fgetc , because I need to check some letters, if to use eg fgets then it will stop on first nl , which function to use? Maybe I don't get something, is it possible in general?

I already have rLine function for reading line ( using fgetc ):

char * rLine( int * length, int * ha ){
   char *buff = malloc( LMAX ), *old = buff;
   int count = 0, maxlen = LMAX, len = maxlen, c;

    while ( (c = fgetc( stdin ) ) != '\n' ){

       if ( c == EOF ) { *ha = R_EOF; break; }

       if ( /* some conditions for c */ ) *ha = R_FALSE;

    *buff ++ = c;
     count++;

     if ( -- len == 0 ){  
       len = maxlen;
       buff = (char *)realloc( old, maxlen *= 2 );
       old = buff;
       buff += count;
   }
 }
 *length = count;
 *buff = '\0';
 return old;
}

, where ha some kind of error-message handler. Tnx

NOTE: OK, I've found out that end of input is driven same as CTRL + D combination. so actually the check if ( c == EOF ) ( or c == '\\0' ) works fine for me. So actually the question can be closed by now.

Are you familiar with '\\n' for a new line and '\\r\\n' for carriage return?

add this line and handle the new line case:

  if ( c == '\n' ) { // that is a new line }

Have you seen this post:

How to read a line from the console in C?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM