c++ - Using two string streams but not getting same result -


i'm trying make , print matrix getting data text file. able make output aligned (i.e. of matrix), extracted data files strings first using stringstream largest number of characters element have in matrix. afterwards, put string stringstream extracted them double, per specifications of project. problem is, whenever have data in text file separated whitespace (not new line), gets first element of line.

while(getline(file, line) && size < (rows*columns)) {   stringstream s1(line);   stringstream s2;   string temp;   double toadd;    while(s1 >> temp && size < (rows*columns))    {     if(temp.size() > columnwidth2)       columnwidth2 = temp.size();      s2 << temp;     s2 >> toadd;      cout << "size: " << size << "\nto add: " << toadd << "\ntemp: " << temp << '\n';     datacontainer[size] = toadd;     size++;     s2.str(string());   } } 

for example, have text file data:

1 2 3 4 5 6 7 8 9 10 

if output contents of datacontainer, reads:

1 1 1 1 1 6 7 8 9 10 

instead of:

1 2 3 4 5 6 7 8 9 10 

what doing wrong?

why don't use

while(s1 >> toadd && size < (rows*columns))  

instead of

while(s1 >> temp && size < (rows*columns))  

or, can define stringstream s2 in inside while block this:

while(s1 >> temp && size < (rows*columns))    {     if(temp.size() > columnwidth2)       columnwidth2 = temp.size();     stringstream s2;     s2 << temp;     s2 >> toadd;      cout << "size: " << size << "\nto add: " << toadd << "\ntemp: " << temp << '\n';     datacontainer[size] = toadd;     size++;     s2.str(string());   } 

the best way this, add s2.clear() after s2.str(""), clear() can reset error state in stringstream(in case: eof)... because called operator>> right after operator<<, s2 reached end-of-file , had eof state set. according c++ refference, if attempt read end-of-file, fail, , "fail state" set up. reason why s2 can gets first element. here codes modify:

  while(s1 >> temp && size < (rows*columns))    {     if(temp.size() > columnwidth2)       columnwidth2 = temp.size();     s2 << temp;     s2 >> toadd;      cout << "size: " << size << "\nto add: " << toadd << "\ntemp: " << temp << '\n';     datacontainer[size] = toadd;     size++;     s2.str(string());     s2.clear(); //it can clear eof state   } 

Comments