这只是一个简单的程序,试图获取字符直到输入“ 0”。但是,当我在Code :: Blocks 17.12上执行此操作时,终端似乎总是在打印输入的字符之前得到两个字符作为输入。
char temp;
do {
printf("Enter character: ");
scanf("%c ",&temp);
printf("Character entered: [%c]\n",temp);
}while(temp!='0');
我得到的结果是
Enter character: a
b
Character entered: [a]
Enter character: c
Character entered: [b]
Enter character: d
Character entered: [c]
Enter character: e
Character entered: [d]
Enter character: 0
Character entered: [e]
Enter character: 0
Character entered: [0]
我的预期结果是
Enter character: a
Character entered: [a]
Enter character: b
Character entered: [b]
Enter character: c
Character entered: [c]
Enter character: c
Character entered: [c]
Enter character: 0
Character entered: [0]
答案 0 :(得分:3)
问题是您要求scanf
跳过格式字符串中的后缀空格。为了使scanf
知道尾随空格在何时何地结束,必须有一些不是空格的输入。
解决方案是跳过格式为" %c"
的前导空格。