Manage input values from file according to number of elements per line I was given the a test file with the following kind of content, an arbitrary number of integer pairs divided by a newline and a final line with one integer:

1 2
3 4
5


I had to use the couples as values for two data members of a series of objects and I had to put the last integer in a separate variable.

I eventually wrote a working code, but the second inner while loop is very wasteful (it is the one loading the last value).

Also, I had to include &lt;fstream&gt;, &lt;sstream&gt; and &lt;string&gt; just to manage this input file.

What is a simpler and more elegant way to solve this problem?

#include &lt;iostream&gt;
#include &lt;fstream&gt;
#include &lt;sstream&gt;
#include &lt;vector&gt;
#include &lt;string&gt;

class anObject
{
public:
    int one;
    int two;
};
int main()
{
    std::ifstream inFile;
    inFile.open("myFile.txt", std::ios::in); 

    int myVar=0;
    std::string inLine;   

    while (getline(inFile, inLine))
    {
        int inputA, inputB;
        std::stringstream inStream(inLine);
        std::stringstream inStreamAlt(inLine);

        while (inStream &gt;&gt; inputA &gt;&gt; inputB)
        {
            anObject inObj;
            inObj.one = inputA;
            inObj.two = inputB;
            objList.push_back(inObj);
        }

        while (inStreamAlt &gt;&gt; inputA)
        {
            myVar = inputA;
        }
    }
}
You can simplify your loops logic like this

while (getline(inFile, inLine)) {
    std::istringstream inStream(inLine);

    anObject inObj;
    if((inStream &gt;&gt; inObj.one) &amp;&amp; (inStream &gt;&gt; inObj.two)) {
        objList.push_back(inObj);
    }
    else {
        myVar = inObj.one;
    }
}


relying on exactly that form of input you mentioned is given.



std::ios::in is redundant for std::ifstream:

inFile.open("myFile.txt", std::ios::in); 
                     // ^^^^^^^^^^^^^^


also open() isn't explicitely needed. You can simply write:

std::ifstream inFile("myFile.txt"); 




class anObject
{
public:
    int one;
    int two;
};


can be simpler written as struct:

struct anObject
{
    int one;
    int two;
};