0

I 'm doing an exercise at http://www.spoj.com/problems/RETO7/, but I got stuck on reading the inputs, the count of input lines is unknown, each line has two number, there is also empty line, can anyone know the way to solve this problem. The input is pasted to the console.

The webpage I mentioned above provide us a machine to run code(for any problems that be also listed on the page). We can communicate with its input file through standard in standard out. For exam, for adding two integers exercise, the input contains lines follow the rules, the first line is the number of pairs of int to be calculate called n, the next n line each line has two integers. The out put is n lines each line contains the sum of pairs of integers above. To solve this problem, the code below is alright

#include <iostream>
using namespace std;

int main()
{
    int n,i,a,b;
    cin>>n;
    for(i=0;i<n;i++)
    {
        cin>>a>>b;
        cout<<a+b<<endl;
    }
    //fflush(stdin);
    //getchar();
}

But now the input rules is changed, there is no first line with the number of sum to be calculate, so I don't know how many call to "cin" to be made. And I'm looking for a solution of reading all the inputs , I just want it to only calculate for the input I paste to the console and nomore inputs after that. The input I paste for the code above is

7
1 2
3 4
5 6
7 8
9 10
23 34
56 67

and the result

3
7
11
15
19
57
123

ps:I don't realy know if the input may contain empty line,but in the example they provided it does Thanks for reading!

StephenKhoa
  • 105
  • 8
  • 2
    Please post what you have tried so far, preferably a [mcve], and indicate where you are running into problems. – R Sahu Jun 02 '18 at 04:06
  • Have you tried using Google ("c++ read to end of file")? Just make sure you avoid the [`while(file.eof())` mistake](https://stackoverflow.com/q/5605125/9254539). – eesiraed Jun 02 '18 at 04:06
  • https://stackoverflow.com/questions/20756968/reading-multiple-lines-from-a-file-using-getline – macroland Jun 02 '18 at 05:47
  • Instead of trying to write a program in a language you don't know how to use, would it not be better to find a book/tutorial to study? – Galik Jun 02 '18 at 05:57

1 Answers1

1

I'm so stupid, finally I found a solution

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string str;
    int a,b;
    do
    {
        getline(cin,str);
        if(str!="")
        {
            stringstream ss(str);
            ss>>a>>b;
            //do something
        }
    }
    while(str!="");
    fflush(stdin);
    getchar();
}
StephenKhoa
  • 105
  • 8