C

时间:2016-10-08 18:26:07

标签: c scanf

我自己学习如何使用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]

有人能解释我为什么会这样吗?

1 个答案:

答案 0 :(得分:1)

line feed作为第二个字符的输入。您可以再次使用inputTwo来阻止它:

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);
  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);
  }

}