Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple summation program on cpp

Tags:

c++

c++11

eof

cin

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?

like image 686
giulio Avatar asked Nov 21 '25 06:11

giulio


2 Answers

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.

like image 55
shauryachats Avatar answered Nov 22 '25 19:11

shauryachats


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;
}
like image 28
Ganesh Kamath - 'Code Frenzy' Avatar answered Nov 22 '25 20:11

Ganesh Kamath - 'Code Frenzy'



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!