Reputation: 23
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;
}
Upvotes: 0
Views: 1105
Reputation: 7925
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;
}
Upvotes: 1