【问题标题】:Neverending while-loop in C++ that is to end when an input string == no?C ++中永无止境的while循环是在输入字符串==否时结束?
【发布时间】:2017-05-29 10:56:37
【问题描述】:

我正在尝试编写一个将两个输入整数相加的代码,并且只要用户愿意,就一直添加一个整数,如果用户想退出,只需写“否”。但是,这不起作用。当您写“不”时,它会变得疯狂并添加和减去看似随机的数字。我的主要功能只是运行inputIntegersUsingLoopAndPrintSum()

void inputIntegersUsingLoopAndPrintSum() {
    int input;
    string answer;

    int sum = inputIntegersAndPrintSum();

    cout << "do you wish to continue? if you don't; write no\n";
    getline(cin, answer); //If you wish to continue
    while (answer != "no") {
        input = inputInteger();
        sum = sum + input;
        cout << "new sum is: " << sum << "\n";
        cout << "do you wish to continue? if you don't; write no\n";
        getline(cin, answer);   
    }


    int inputInteger() {
       int tall;
       cout << "Skriv inn et tall: "; 
       cin >> tall;
       return tall;

       int inputIntegersAndPrintSum() {
           int input1, input2, sum;
           input1 = inputInteger(); //bruker den som returnere en verdi
           input2 = inputInteger();

           sum = input1 + input2;
           cout << "Summen av tallene: " << sum << "\n";
           return sum;
       }

【问题讨论】:

  • 不要混用 getline&gt;&gt;。这是灾难的根源。
  • 您是否尝试过打印answer 总是循环运行?写while(answer != "no"){ cout&lt;&lt;answer&lt;&lt;endl; ... 之类的东西,然后检查你得到了什么。
  • 可能当您在方法inputInteger() 中使用cin 时,当您在answer 上调用getline 时可能会导致一些错误
  • 它只是简单地替换了我一直在使用的 getlines。我第一次这样做时它没有编译,但在重新启动视觉后它工作了。感谢您的帮助!

标签: c++ string while-loop


【解决方案1】:

我认为你想多了...看看这个简短的节目。

#include <iostream>

int main() {
    char choice = ' ';
    unsigned value = 0;
    unsigned temp = 0;
    std::cout << "Enter a value to be added to." << std::endl;
    std::cin >> value;

    do {
        std::cout << "Enter another value." << std::endl;
        std::cin >> temp;

        value += temp;

        std::cout << value << std::endl;

        std::cout << "Would you like to continue (Y/N)?" << std::endl;
        std::cin >> choice;

    } while ( choice == 'Y' || choice == 'y' );

    return 0;
}

【讨论】:

  • 这里唯一的区别是只要用户按下Yy,它就会继续,其他任何东西都会评估为假,包括Nn,因为我只得到一个单个字符。这可以扩展为接受和检查字符串或字符数组,只需调整 while 循环表达式或语句中的条件。
猜你喜欢
  • 2019-03-03
  • 2023-03-22
  • 2015-08-23
  • 2018-06-25
  • 1970-01-01
  • 2022-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多