我是编程新手,正在尝试自学 C。然而我遇到了一个我不知道如何解决的问题。这是我的简单程序。抱歉语法错误英语是我的第二语言。
int main(){
int x, confirmation;
do{
printf("\nTest Data: ");
scanf("\n%d ", &x);
printf("Do you want to stop? Y/N");
confirmation = getchar();
}while(confirmation != 'Y');
return 0;
}
顺便说一句,这是在 Codeblocks 中。
执行程序“测试数据:”和“scanf”都可以,但在执行第二个“printf”之前它首先要求“getchar”。除此之外,程序工作正常,当我输入“Y”时,它应该结束,但不是在执行第二个“printf”之前。像这样:
在使用 getchar 之前我使用过 scanf("%c",...) 但问题是一样的。我也尝试过“while”循环。
这是因为
scanf
后面有空格,所以卡在了%d
里。删除该空格,然后阅读,直到到达换行符。它可能看起来像这样:
#include <ctype.h>
#include <stdio.h>
int main(void) {
int x, confirmation;
int ch;
do {
printf("\nTest Data: ");
if (scanf("%d", &x) != 1) break; // no \n or space
printf("Do you want to stop? Y/N");
// read until the newline:
while((ch = getchar()) != EOF && ch != '\n') {}
if (ch == EOF) break;
confirmation = getchar();
} while(toupper((unsigned char)confirmation) != 'Y');
}