【问题标题】:user initiated looping in c++ [duplicate]用户在c ++中启动循环[重复]
【发布时间】:2014-11-30 19:26:15
【问题描述】:

我想编写一个程序,它接受用户的输入并计算三角数。还应该有一个选项来询问用户是否要进行另一个输入或退出,并且需要使用 while 或 do...while 来完成。我编写了以下代码,但没有达到预期的效果:

#include <stdio.h>
int main(void)
{
    int n, number, triangularNumber;
    char s = 'Y';
    while (s == 'Y') {
        printf("What triangular number do you want? ");
        scanf("%i", &number);
        triangularNumber = 0;
        for (n = 1; n <= number; ++n)
            triangularNumber += n;
        printf("Triangular number %i is %i\n\n", number, triangularNumber);
        printf("Do you want to continue?\n");
        scanf("%c", &s);
    }
    return 0;
}

上面的代码只执行一次,然后退出。如何根据我提供的输入让它再次运行循环?提前致谢。

【问题讨论】:

  • 当用户按下y 时,它是否以小写形式出现?这可能是它在 1 个循环后爆炸的原因,如果是这样,你可以很容易地调试它

标签: c++ visual-studio-2013


【解决方案1】:

scanf("%i",&amp;number); 生成一个换行符,供您的 scanf("%c",&amp;s); 使用
重写为scanf(" %c",&amp;s)(在%c之前包含一个空格)以忽略输入前的所有空格。

【讨论】:

    【解决方案2】:

    两个问题:首先是小写字母和大写字母的区别,'y' != 'Y'

    第二个问题,也就是您在这里看到的,是您读取数字的第一个scanf,它将换行符留在输入缓冲区中。然后第二个scanf 调用读取该换行符并将其写入变量s

    第一个问题可以通过使用toupper确保变量s的内容是大写字母来轻松解决:

    while (toupper(s) == 'Y') { ... }
    

    第二个问题可以通过要求scanf在获取字符时读取并丢弃前导空格来轻松解决,只需在格式代码前添加一个空格即可:

    scanf(" %c", &s);
    //     ^
    //     |
    // Note space here
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-25
      • 1970-01-01
      • 1970-01-01
      • 2012-06-02
      • 1970-01-01
      相关资源
      最近更新 更多