【发布时间】:2016-10-08 18:26:07
【问题描述】:
我正在自学如何使用 C 语言编写代码。为了更深入地研究后者,我正在做一些基本的练习,因此,今天我在使用scanf() 指令时遇到了一个小问题。其实如下代码:
int main() {
char inputOne;
char inputTwo;
printf("Insert a char: ");
scanf("%c", &inputOne);
// &inputOne is the pointer to inputOne.
printf("Insert another char: ");
scanf("%c", &inputTwo);
if (inputOne == inputTwo) {
printf("You have inserted the same char!\n");
printf("Chars inserted: %c, %c\n", inputOne, inputTwo);
} else {
printf("You have inserted two different chars!\n");
printf("Chars inserted: %c, %c\n", inputOne, inputTwo);
}
}
编译时不会返回任何错误,但是当我在终端上启动应用程序时,我无法插入第二个字符。 下面是一个例子:
Macbook-Pro-di-Rodolfo:~ Rodolfo$ /Users/Rodolfo/Documents/GitHub/Fondamenti\ di\ C/esempio-if-else ; exit;
Insert a char: a
Insert a second char: You have inserted two different chars!
Chars inserted: a,
logout
[Process completed]
谁能解释一下为什么会这样?
【问题讨论】:
-
这个问题的 数百个 重复项之一can be found here.
-
@user3121023 转换规范前后的空格数会影响最终结果吗?换句话说,
scanf(" %c", &inputTwo)和scanf(" %c", &inputTwo)对于编译器是否相同? -
@user3121023 很抱歉,我的第一条评论中没有正确显示它,但我的意思是如果
scanf()的行为方式与引号和转换规范%。换句话说,如果<space><space><space>%c和<space>%c输出相同的东西。