[英]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.