【问题标题】:Issue with scanf() in CC 中的 scanf() 问题
【发布时间】: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 输出相同的东西。

标签: c scanf


【解决方案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);
  }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-21
    • 2011-07-21
    • 2021-12-29
    • 2011-08-13
    • 2021-11-14
    • 2019-04-15
    相关资源
    最近更新 更多