#include <stdio.h>
int main()
{
char c = 'A';
while (c != ',')
{
printf("Input a character:");
scanf("%c", &c);
if (c >= '0' && c <= '9')
{
printf("%d\n", (int)c);
}
}
}
接受第一组输入后,这段代码每次都会打印两次“输入一个字符” - 这是为什么?
最佳答案
因为你按下一个数字加上 Enter,并且 Enter 将在下次调用时被 scanf()
读取
#include <stdio.h>
int main(void) {
char c = 'A';
while (c != ',') {
printf("Input a character:");
if (scanf("%c", &c) != 1) {
return 0; // we stop if user don't input anything
}
if (c >= '0' && c <= '9') {
printf("%d\n", (int)c); // by the way did you want (int)(c - '0') ?
} else {
printf("enter a number ! you enter %d\n", c);
}
}
}
关于c - 为什么这个c程序打印两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47062702/