简体   繁体   English

C 中 scanf() 的问题

[英]Issue with scanf() in C

I am learning by myself how to code using the C languange.我正在自学如何使用 C 语言进行编码。 In order to study this latter a bit more in depth, I'm doing some basic exercises and, due to this, today I have faced a little issue using the scanf() instruction.为了更深入地研究后者,我正在做一些基本练习,因此,今天我在使用scanf()指令时遇到了一个小问题。 Infact, the following code:事实上,以下代码:

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

}

when compiled does not return any error, but when I launch the application on the Terminal, I am not able to insert the second character.编译时不返回任何错误,但是当我在终端上启动应用程序时,我无法插入第二个字符。 Here is an example of what happens:以下是发生的情况的示例:

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 anybody explain me why this happens?谁能解释一下为什么会发生这种情况?

It takes line feed as input to the second character.它将line feed作为第二个字符的输入。 You can take the inputTwo again to prevent it:您可以再次使用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);
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM