-3

I'd like to make a program that keeps reading numbers until there is an empty input. What I mean by that is the following:

12 <ENTER> 
24 <ENTER> 
<ENTER> 
Sum of these numbers is: 36

So far I've got this:

#include<iostream>

using namespace std;

long double sum = 0, num = 0;
string junk;

int main(){
    cout << "Witaj w programie do liczenia sredniej!\n\n";
    while (true){
        while (cin >> num){ //stops when you input a char
            sum += num;
        }
        cin.clear();
        getline(cin, junk);
        cout << "\nSuma tych liczb to: " << sum << "\n\n";
    }
    return 0;
}

It works this way:

12<ENTER>
24<ENTER>
q<ENTER>
Sum of these numbers is: 36

If something is unclear let me know and I'll try to improve. Any help appreciated :)

TheHardew
  • 399
  • 4
  • 12
  • Have a look here: [How to test whether stringstream operator>> has parsed a bad type and skip it](http://stackoverflow.com/questions/24504582/how-to-test-whether-stringstream-operator-has-parsed-a-bad-type-and-skip-it). This may help for your problem also. Note that ENTER (`'\n'`) is actually ignored by `cin >> ...`, unless you change the standard delimitier. – πάντα ῥεῖ Aug 27 '14 at 09:41
  • I know it's ignored, I know also that u can change it using "noskipws" but I thought there is something that is able to recognize if there is nothing entered – TheHardew Aug 27 '14 at 09:46

1 Answers1

4

In your code I cannot see checking of newline. See my code, it seems to work fine. Maybe it is solution which you are looking for.

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    int sum = 0;
    string line;

    while (getline(cin, line))
    {
        stringstream ss(line);
        int tmp;

        if (ss >> tmp)
        {
            sum += tmp;
        }
        else
        {
            break;
        }
    }

    cout << "\nSuma tych liczb to: " << sum << "\n\n";

    return 0;
}
Dakorn
  • 883
  • 6
  • 11