简体   繁体   English

在C ++中,无休止的while循环将在输入字符串==否时结束?

[英]Neverending while-loop in C++ that is to end when an input string == no?

I am trying to write a code that sums two input integers, and keeps on adding an integer for as long as the user wishes to do so, and if the user wants to exit simply writes "no". 我正在尝试编写一个将两个输入整数相加的代码,并且只要用户希望这样做就一直加一个整数,如果用户要退出,则只需写“ no”。 This does not work, however. 但是,这不起作用。 When you write "no" it just goes crazy and adds and subtracts seemingly random numbers. 当您写“ no”时,它会变得疯狂并增加和减少看似随机的数字。 My main function simply runs inputIntegersUsingLoopAndPrintSum() 我的主要功能只是运行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;
       }

I think you are over thinking this... check out this short program. 我认为您想得太过分了...请查看此简短程序。

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

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

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