[英]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.