giulio
giulio

Reputation: 659

Simple summation program on cpp

I am trying to get a c++ program sum the elements 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 on c++ primer, but when I compile this program and run it, the prompt keeps waiting for inputs. Why is it not outputting anything?

Upvotes: 3

Views: 451

Answers (2)

shauryachats
shauryachats

Reputation: 10385

std::cin keeps waiting for an input until it encounters EOF (End-of-File). When you run it in a terminal (Linux), you just have to press Ctrl + D to generate EOF. If you are a Windows user, use Ctrl + Z.

Upvotes: 6

Please set a limit on the values and check it in the 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 would be to take the number of entries 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;
}

Upvotes: 4

Related Questions