【问题标题】:Printf happens twice in while loop? [duplicate]Printf 在 while 循环中发生两次? [复制]
【发布时间】:2017-09-17 20:11:27
【问题描述】:

所以我是编程的初学者,我想我会尝试制作一个基本的计算器,它可以给出两个数字的总和或乘积。然而,在这个程序的while 循环中,第一个printf 似乎在循环的第一次迭代之后打印了两次。任何纠正此问题的帮助将不胜感激。

#include <stdio.h>
#include <string.h>

int multiply(int a, int b) {
    return a * b;
}

void printMultiply(int x, int y) {
    int result = multiply(x, y);
    printf("\n%d\n", result);
}

int add(int a, int b) {
    return a + b;
}

void printAdd(int x, int y) {
    int result = add(x, y);
    printf("\n%d\n", result);
}

int main() {
    int product1 = 0;
    int product2 = 0;

    int sum1 = 0;
    int sum2 = 0;

    while (true) {
        // this prints twice after first iteration?
        printf("Would you like to add or multiply? (press a or  m)\n");

        char choice = ' ';
        scanf("%c", &choice);

        if (choice == 'm') {
            printf("What two numbers would you like to multiply? (leave a space between numbers\n");
            scanf("%d%d", &product1, &product2);
            printMultiply(product1, product2);
        } else
        if (choice == 'a') {
            printf("What two numbers would you like to add?  (leave a space between numbers\n");

            scanf("%d%d", &sum1, &sum2);
            printAdd(sum1, sum2);
        }
    }
}

【问题讨论】:

  • 您可能从 scanf 中点击了换行符,因为它不属于您循环的已知选择。
  • scanf(...) 正在对看不见的返回字符做出反应。尝试在格式字符串前面放置一个空格字符以使用 return (newline) 字符:scanf(" %c", &amp;choice);

标签: c printf


【解决方案1】:

在第一次迭代之后,您会在第一次调用 scanf 时看到一个换行符 (\n)。

您需要做的就是在格式字符串中使用前导空格来占用所有空格:

scanf(" %c", &choice);

【讨论】:

  • 这对我来说很奇怪。我使用 std::cin 进行了这项工作,没有任何问题,这就是让我失望的原因。所以在两个数字后按“回车”意味着scanf下一轮会自动读取\n?
  • 是的。您需要在某处使用换行符。这是scanf 的常见问题。
【解决方案2】:

'\n' 在第一次迭代后输入到 ch。 从缓冲区中删除它。

scanf("%d%d", &sum1, &sum2);

scanf("%c", &enter);

【讨论】:

    【解决方案3】:

    试试这个:

    scanf("\n%c", &choice);
    

    这会解决你的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-03
      • 1970-01-01
      相关资源
      最近更新 更多