[英]Neverending while-loop in C++ that is to end when an input string == no?
我正在嘗試編寫一個將兩個輸入整數相加的代碼,並且只要用戶希望這樣做就一直加一個整數,如果用戶要退出,則只需寫“ no”。 但是,這不起作用。 當您寫“ no”時,它會變得瘋狂並增加和減少看似隨機的數字。 我的主要功能只是運行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;
}
我認為您想得太過分了...請查看此簡短程序。
#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.