简体   繁体   English

C从stdin读取行,方法是按Enter

[英]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: 我正在用C编写用于项目的程序,在这里我有这样的输入:

  ............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. 第一组数据与第二组数据用空行分隔,我需要在一个Enter上进行处理。

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. 如果我将这些数据复制粘贴到终端窗口中,然后按Enter ,然后按Ctr + D(表示输入结束),则可以正常工作,但是如果仅按Enter ,则仍然需要输入数据。 I can't understand what to change so only on first Enter I'll finish input and proceed to my program? 我不知道要更改什么,所以仅在第一次Enter完成输入并继续执行程序? 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? 我知道这个问题听起来很愚蠢,但是在我阅读行的函数中我使用fgetc ,因为我需要检查一些字母,如果要使用例如fgets ,它将在第一个nl停止,要使用哪个函数? Maybe I don't get something, is it possible in general? 也许我什么都没得到,总的来说可能吗?

I already have rLine function for reading line ( using fgetc ): 我已经有了rLine函数来读取行(使用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. 其中ha某种错误消息处理的。 Tnx 特纳克斯

NOTE: OK, I've found out that end of input is driven same as CTRL + D combination. 注意:好的,我发现输入的结尾与CTRL + D组合相同。 so actually the check if ( c == EOF ) ( or c == '\\0' ) works fine for me. 所以实际上检查if ( c == EOF ) (或c == '\\0' )对我来说还不错。 So actually the question can be closed by now. 因此,实际上,这个问题现在可以解决。

Are you familiar with '\\n' for a new line and '\\r\\n' for carriage return? 您是否熟悉'\\n'换行和'\\r\\n'换行?

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? 如何从C中的控制台读取一行?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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