gpt4 book ai didi

c++ - C++ 中永无止境的 while 循环,即在输入字符串 == no 时结束?

转载 作者:行者123 更新时间:2023-11-28 05:20:24 27 4
gpt4 key购买 nike

我正在尝试编写一个对两个输入整数求和的代码,并在用户希望这样做时一直添加一个整数,如果用户想退出,只需写“否”即可。但是,这不起作用。当你写“不”时,它就会变得疯狂,并添加和减去看似随机的数字。我的主要功能只是运行 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;
}

关于c++ - C++ 中永无止境的 while 循环,即在输入字符串 == no 时结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41645292/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com