如何用更少的参数停止 scanf
我需要不断从键盘获取 3 个值(int、int、float),并且只有在输入 0 时才停止循环。
问题是,当我输入 0 并按 [Enter 时,它会一直等待第二个和第三个值。
int i, j; float v;
while (scanf("%i %i %f", &i, &j, &v) == 3){
Matrix* M = (Matrix*)malloc(sizeof(Matrix));
M->line = i;
M->column = j;
M->info = v;
printf("loop");
}
我知道 scanf 返回一个整数,表示成功捕获的值的数量,问题是:如何停止等待新输入并返回已捕获的数量。 (所以在这种情况下我可以退出循环。)
I need to keep getting 3 values (int, int, float) from the keyboard and only stop the loop when I enter 0.
The problem is that when I enter 0 and press [Enter it keeps waiting for the second and third value.
int i, j; float v;
while (scanf("%i %i %f", &i, &j, &v) == 3){
Matrix* M = (Matrix*)malloc(sizeof(Matrix));
M->line = i;
M->column = j;
M->info = v;
printf("loop");
}
I know that scanf returns an integer representing the number of successfully captured values, the question is: How to stop waiting for new inputs and return the number of already captured. (So i can exit the loop in this case.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会考虑只读取循环中的整行,然后在循环内使用 sscanf 解析该行。返回值 1 和解析为
0
的第一个值将指示您想要的结束条件。当您拥有完整的产品线时,您还可以提供更好的错误诊断。I would consider just reading whole lines in the loop and then parsing that line using
sscanf
inside the loop. Return value 1 and the first value parsed as0
would indicate your desired ending condition. When you had the complete line available, you could also present better error diagnostics.正如其他人所建议的,您可以尝试一下:
仅输入
0
或q
将退出循环。As suggested by others, would you please try:
Entering just
0
orq
will exit the loop.