简体   繁体   中英

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". This does not work, however. When you write "no" it just goes crazy and adds and subtracts seemingly random numbers. My main function simply runs 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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