I've just started (yesterday) learning how to code in C++ and I'm following Lippman's 'C++ Primer' book.
He gives us this code bit:
#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; // equivalent to sum = sum + value
std::cout << "Sum is: " << sum << std::endl;
return 0;
}
Works fine. Now, one of the exercises is to write my own version of a program that prints the sum of a set of integers read from cin. I'm trying to do that using a for statement. Right now I have this:
#include <iostream>
int main(){
int sum = 0;
std::cout << "Please insert your values. When you want to terminate, insert the number 0." << std::endl;
for(int val1; val1 != 0; std::cin >> val1)
sum += val1;
std::cout << "The sum of your inputs is " << sum << std::endl;
return 0;
}
To avoid having to crtl + z to end the program, I'm trying to add a condition in which when the user inputs the number zero the program outputs the sum of all the inputs and terminates. For some reason, the sum I get is always wrong, i.e., I input 9 and 9 and the sum outputs 16.
In summarizing, I want the user to keep inputing numbers until he doesn't want to anymore (inputs the number zero), at which point the program calculates the sum of all former inputs and outputs the result.
Thanks in advance for the help.
The for statement can look the following way
for ( int val1; std::cin >> val1 && val1 != 0; )
sum += val1;
As for your for statement
for(int val1; val1 != 0; std::cin >> val1)
sum += val1;
then first of all variable val1 initially was not initialized so the loop is wrong. And you have to check whether operation std::cin >> val1 was successfull.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With