Search code examples
c++fileioifstream

Reading lines with 2 numbers each in C++


I'm pretty rusty on my C++. I'm wondering what the best way is to read input in the following format:

400 200
138 493
...

I'm currently using while(cin.peek()!=-1) to check for EOF, and then within that, I'm using while(cin.peek()!='\n') to check for newlines. This is fine for reading in full lines of text, but how can I limit it to 2 numbers and/or grab just those 2 numbers?


Solution

  • int num1,num2;
    while(cin>>num1>>num2)
    {
         //...
    }
    

    or

    string line;
    int num1,num2;
    stringstream ss;
    while(getline(cin,line))
    {
        ss<<line;
        ss>>num1>>num2;
        //...
    }