以下代码给出运行时错误,我只是找不到代码中的问题。那么是否有人可以提供帮助?
#include<stdio.h>
int main() {
int a = 0;
while(1){
scanf("%d",&a);
if(a==42)
break;
printf("%d\n",a);
}
return 0;
}
最佳答案
如果您想扫描用户输入直到按下有效输入,您可以使用以下代码:
#include <stdio.h>
int main() {
char a = 0;
while(1){
scanf("%c",&a);
if(a==42)
break;
printf("%d\n",a);
}
return 0;
}
此代码不会卡在任何输入上,但它会逐个字符地处理输入,因此您可能会因为输入而在控制台上看到类似 10
的内容。要结束此程序,如果我们有 ascii 编码,则有效的用户输入是 *
。
正如您在 scanf
man page 中看到的那样:
On success, these functions return the number of input items successfully matched and assigned; this can be fewer than provided for, or even zero, in the event of an early matching failure.
它将返回成功匹配输入的数量,以便您可以检查该值以确保您的代码在输入缓冲区上取得进展。
关于c - C程序运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44487729/