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 23 45I 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 <fstream>, <sstream> and <string> just to manage this input file.What is a simpler and more elegant way to solve this problem?#include <iostream>#include <fstream>#include <sstream>#include <vector>#include <string>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 >> inputA >> inputB)        {            anObject inObj;            inObj.one = inputA;            inObj.two = inputB;            objList.push_back(inObj);        }        while (inStreamAlt >> inputA)        {            myVar = inputA;        }    }}
Manage input values from file according to number of elements per line
c++;formatting;io;stream
You can simplify your loops logic like thiswhile (getline(inFile, inLine)) {    std::istringstream inStream(inLine);    anObject inObj;    if((inStream >> inObj.one) && (inStream >> 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;};