Spy*_*tis 2 c user-input input scanf getchar
我有下面的代码,它应该与用户交互,了解他想要做什么。
int input;
printf("Would you like to update the name of the student?\n");
printf("Enter Y(yes) or N(no)\n");
input = getchar();
if (input == 'Y' || input == 'y') {
printf("Please enter the updated name\n");
scanf("%s", tmpSt->name);
}
printf("Would you like to update the student's ID?\n");
printf("Enter Y(yes) or N(no)\n");
input = getchar();
Run Code Online (Sandbox Code Playgroud)
但执行时它不会停止获取第一个输入。
Would you like to update the name of the student?
Enter Y(yes) or N(no)
Would you like to update the student's ID?
Enter Y(yes) or N(no)
Run Code Online (Sandbox Code Playgroud)
它应该得到名称的答案,但它直接转到 ID。
scanf("%s", ...)将用户输入的换行符保留在输入流中。
而不是getchar(),使用char c; scanf(" %c", &c);初始空格将使scanf()忽略待处理的空白,包括待处理的换行符。
还要检查返回值scanf()以检测无效输入和文件结尾。