我有这样的条目:
0 5 260
1 0 -598
1 5 1508
2 1 -1170
我以前不知道我会得到多少(控制台)输入,所以我必须阅读直到没有剩余条目。
我从这样的代码开始:
int a, b, c;
while(scanf("%d %d %d", &a, &b, &c)!=EOF){
// do stuff here
}
但它永远不会停止请求新的输入。
然后,我看到其他线程中的人提出了这个建议:
int a, b, c;
while(scanf("%d %d %d", &a, &b, &c)==1){
// do stuff here
}
在这种情况下,它甚至没有进入 while。
有人知道我做错了什么吗?
一种方法:继续请求输入,直到输入关闭(EOF)或遇到问题。 (无效的输入行)
下面使用 fgets()
读取一行。
然后,"%n"
检测扫描停止的位置。如果扫描没有到达 %n
,n
的值仍然为 0。否则它会在扫描停止的地方获取 buffer
中的偏移量,希望如此它位于空字符 '\0'
处。
char buffer[100];
while (fgets(buffer, sizeof buffer, stdin)) {
int n = 0;
sscanf(buffer, "%d%d%d %n", &a, &b, &c, &n);
if (n == 0) {
fprintf(stderr, "3 int were not entered\n");
break;
}
if (buffer[n] != 0) {
fprintf(stderr, "Extra input detected.\n");
break;
}
// do stuff here with a,b,c
}
有很多方法可以解决这个问题。
我是一名优秀的程序员,十分优秀!