我正在尝试从用户那里获取两个字符。但我得到一个错误。让我解释一下。
当我编译并运行这段代码时:
#include <stdio.h>
int main(){
char ch1,ch2;
printf("Enter the first character: ");
scanf("%c",&ch1);
printf("Enter the second character: ");
scanf("%c",&ch2);
printf("The characters are %c and %c",ch1,ch2);
return 0;
}
我得到这个输出:
Enter the first character: 1
Enter the second character: The characters are 1 and
我无法输入第二个字符。但是当我这样做时:
Enter the first character: 12
Enter the second character: The characters are 1 and 2
如果我输入 12,程序会将“1”作为第一个字符,将“2”作为第二个字符。
如何在不同时输入两个字符的情况下从用户那里获取两个字符。
最佳答案
%c
会吃掉一个字符,无论是数字还是空格。您可能希望它跳过所有空格然后吃掉一个字符。您可以通过将格式字符串从 %c
更改为 %c
来实现;即在 %c
前插入一个空格。
关于c - 在C中获取两个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32290591/