How does getline() actually behave?

前端 未结 2 1082
夕颜
夕颜 2021-01-29 06:06

I have 2 questions:

  1. What happens to s if I again do a \"getline(in,line)\" after the while loop ends?

    ifstream in(\"string.txt\");
    string s, lin         
    
    
            
2条回答
  •  天涯浪人
    2021-01-29 06:40

    getline reads the stream until it encounters the newline character or reaches the end of stream. In latter case, the steam will have its failbit set. This translates to breaking the while loop in your example, because getline returns the (reference to) stream which is get cast to bool, yielding stream's state that is false because of aforementioned failbit.

    In such conditions, subsequent calls to getline will do nothing as the stream is still in the 'fail' state. You could clear it with istream::clear, but since there is no more data in it, it have its failbit set again on next read.

提交回复
热议问题