Lou*_*s93 4 c++ io stringstream
假设stringstream包含James is 4,我可以写一些类似于getline (stream, stringjames, ' ')获取单个单词的内容,但有没有办法知道我已经到达了行尾?
奖金问题!案例1:James is 4
案例2:James is four
如果我正在迭代字符串流中的单词,并且我希望收到一个4的int值,但是我收到了一个字符串,那么检查这个的最佳方法是什么?
您检查返回值以查看它是否为true或false:
if (getline(stream, stringjames, ' '))
// do stuff
else
// fail
Run Code Online (Sandbox Code Playgroud)
至于"奖金问题",你也可以int从流中提取s和东西时做同样的事情.返回值operator>>将评估true读取是否成功,以及false是否有错误(例如有字母而不是数字):
int intval;
if (stream >> intval)
// int read, process
else if (stream.eof())
// end-of-stream reached
else
// int failed to read but there is still stuff left in the stream
Run Code Online (Sandbox Code Playgroud)