0

I am little confused about the stringstream. Here are the two programs which are behaving very differently

int main(){
         stringstream s("1,-5,-10,20,"); 
         int i;
         char ch;
         while(!s.eof()){
            s >> i;
            s >> ch;
            cout<<i<<" " << ch << " " << s.eof() <<endl;
         }
         stringstream s2(string("the cattle was rattled by the battery"));
         string mys;
         while(!s2.eof()){
            s2 >> mys;
            cout<<mys <<" "  << s2.eof() <<endl;
         }
         return 0;


}

The first stream does not stop after the extraction of the last token "," while for the second stringstream s2 it stopped after the extraction of last token battery. Why is the s.eof() behaviour different in these two scenerio?

The answer in the dupliacate questions does not correctly tell why the second while loop is working perfectly below. (for string s2). This is not a duplicate

David
  • 4,016
  • 6
  • 27
  • 39
  • 2
    Classic case of why you should never test `eof` as your loop condition. Just use `while(s)` and `while(s2)`. – paddy Aug 08 '19 at 23:49
  • 1
    Even better: `while(s >> i >> ch)` and `while(s2 >> mys)` – paddy Aug 08 '19 at 23:52
  • can you please tell me why this behaviour happen. BTW your comment #1 is not valid and gives even invalid results for the second while loop – David Aug 08 '19 at 23:57
  • 1
    Yes, the problem is that you do not check whether you read the values correctly before you use them. You just _assume_ that if EOF is not yet encountered then the stream still contains data in the format you're expecting. In the first case, `eof` is not encountered because reading a single `char` value successfully does not extract any more characters from the stream. Conversely, reading a `string` _does_ extract characters because it's looking for whitespace. In this case it hits EOF while reading "battery". If there was a space following "battery" you would have the same issue as loop 1. – paddy Aug 09 '19 at 00:00
  • Thanks @paddy, So what is the best appraoch to handle extraction from stringstream without making the code too complex – David Aug 09 '19 at 00:05
  • 2
    What is wrong with the second suggestion I gave? – paddy Aug 09 '19 at 00:08
  • Thanks, i guess that seems to be elegant, compact and generalized appraoch. – David Aug 09 '19 at 00:13

0 Answers0