Simple cpp summation program
I am trying to get a C ++ program that a user enters:
#include <iostream>
int main(){
int sum = 0, value = 0;
// read until end-of-file, calculating a running total of all values read
while (std::cin >> value){
sum += value;
}
std::cout << "Sum is: " << sum << std::endl;
return 0;
}
I read this example in C ++ primer, but when I compile this program and run it, the request keeps waiting for input. Why doesn't it output anything?
+3
source to share
2 answers
Set the values limit
and test it in a while loop.
Let me add some code to illustrate ...
#include <iostream>
int main(){
int sum = 0, value = 0, limit=5, entries=0;
std::cout << "Enter "<< limit << " digits:";
// read until end-of-file, calculating a running total of all values read
while ((std::cin >> value) && (entries < limit) ){
sum += value;
entries++;
}
std::cout << "Sum is: " << sum << std::endl;
return 0;
}
another option is to take the number of records the user is going to give;
#include <iostream>
int main(){
int sum = 0, value = 0, limit=0, entries=0;
std::cout << "Enter limit:";
std::cin >> limit;
// read until end-of-file, calculating a running total of all values read
while ((std::cin >> value) && (entries < limit) ){
sum += value;
entries++;
}
std::cout << "Sum is: " << sum << std::endl;
return 0;
}
+4
source to share