簡體   English   中英

讀取輸入時程序停止

[英]Program stops while reading input

我通過以下循環讀取輸入

do
{
      i=0;
      do
      {
          line[i]=fgetc(stdin);
          i++;

      }while(i<100 && line[i-1]!='\n' && line[i-1]!=EOF);

      //Parsing input

 }while(line[i-1]!=EOF);

我的輸入看起來像這樣

$GPRMC,123519,A,4510.000,N,01410.000,E,010.0,010.0,120113,003.1,W*4B
$GPRMC,123520,A,4520.000,N,01650.000,E,010.0,010.0,230394,003.1,W*4B
$GPRMC,123521,A,4700.000,N,01530.000,E,010.0,010.0,230394,003.1,W*4F
$GPRMB,A,0.66,L,001,002,4800.24,N,01630.00,E,002.3,052.5,001.0,V*1D
$GPGGA,123523,5000.000,N,01630.000,E,1,08,0.9,100.0,M,46.9,M,,*68

所以我的問題是,在最后一行之后,當它應讀取EOF時,它將line[i]=fgetc(stdin);上停止line[i]=fgetc(stdin); 即使我從文件中復制輸入並將其粘貼到終端中,或者即使我在終端中使用< input.txt運行該程序,但是當我在終端中運行它時,也要粘貼輸入並比手動添加EOF (^ D)停下來。有人可以告訴我哪里出問題了嗎?

將do-while替換為一會,然后嘗試。 找到EOF后將檢查條件,即是說即使在EOF之后,您也正在執行fgetc(stdin),這是不正確的

#include <stdio.h>

int main(int argc, char *argv[]){
    char line[100+1];
    int ch;

    do{
        int i=0;
        while(EOF!=(ch=fgetc(stdin)) && ch !='\n' && i<100){
            line[i++]=ch;
        }
        line[i]='\0';
        if(*line){
            //Parsing input
            printf("<%s>\n", line);
        }
    }while(ch != EOF);

    return 0;
}

您最多要在char行[]中讀取100個字符。 您以讀入的100個字符或'\\n'或EOF結尾。 這是fgets()的規范。

因此,請考慮使用一個與代碼邏輯匹配的fgets()調用。 使用fgets ,等於:

while(fgets(line, 100, stdin)!=NULL )  // get up to \n or 100 chars, NULL return means usually EOF
{
   char *p=strchr(line, '\n');
   if(p!=NULL) *p=0x0;

   // parsing input
}
// here you should also check for NULL caused by system errors and not EOF -- maybe using feof(stdin)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM