在C中获取两个字符
Getting two characters in C
我正在尝试从用户那里获取两个字符。但我得到一个错误。我来解释一下。
当我编译 运行 这段代码时:
#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
会吃掉一个字符,无论是数字还是白色space。您可能希望它跳过所有 whitespace 然后吃掉一个字符。您可以通过将格式字符串从 %c
更改为 %c
来实现;也就是说,在 %c
.
之前插入一个 space
我正在尝试从用户那里获取两个字符。但我得到一个错误。我来解释一下。
当我编译 运行 这段代码时:
#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
会吃掉一个字符,无论是数字还是白色space。您可能希望它跳过所有 whitespace 然后吃掉一个字符。您可以通过将格式字符串从 %c
更改为 %c
来实现;也就是说,在 %c
.