从字符串流输入值

发布于 2024-10-03 17:32:30 字数 204 浏览 6 评论 0原文

是否有一个 while 循环允许我将字符串流的所有值输入到某种数据类型中?例如:

stringstream line;
while(/*there's still stuff in line*/)
{
    string thing;
    line >> thing;
    //do stuff with thing
}

Is there a while loop that allows me to enter in all the values for a stringstream into some datatype? For example:

stringstream line;
while(/*there's still stuff in line*/)
{
    string thing;
    line >> thing;
    //do stuff with thing
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

零時差 2024-10-10 17:32:30

是:

std::stringstream line;
std::string thing;
while (line >> thing)
{
    // do stuff with thing
}

if (line.fail())
{
    // an error occurred; handle it as appropriate
}

流操作(如>>)返回流;这就是允许您链接流操作的原因,例如:

line >> x >> y >> z

流可以用作布尔值;如果流处于良好状态(即,如果可以从中读取数据),则其计算结果为 true;否则其计算结果为false。这就是为什么我们可以使用流作为循环中的条件。

流无法处于良好状态的原因有很多。

其中之一是当您到达流的末尾时(通过测试 line.eof() 来指示);显然,如果您尝试从流中读取所有数据,这就是您完成后期望流所处的条件。

流不会处于良好状态的另外两个原因是如果出现某些内部错误或流上的操作失败(例如,如果您尝试提取整数但流中的下一个数据不代表整数) 。这两个都通过 line.fail() 进行测试。

Yes:

std::stringstream line;
std::string thing;
while (line >> thing)
{
    // do stuff with thing
}

if (line.fail())
{
    // an error occurred; handle it as appropriate
}

Stream operations (like >>) return the stream; this is what allows you to chain stream operations, like:

line >> x >> y >> z

A stream can be used as a boolean; if the stream is in a good state (that is, if data can be read from it), it evaluates to true; otherwise it evaluates to false. This is why we can use the stream as the condition in the loop.

There are a number of reasons a stream will not be in a good state.

One of them is when you reach the end of the stream (indicated by testing line.eof()); obviously, if you're trying to read all the data out of the stream, this is the condition you expect the stream to be in when you are done.

The other two reasons a stream will not be in a good state are if some internal error or if an operation on the stream failed (for example, if you try to extract an integer but the next data in the stream does not represent an integer). Both of these are tested by line.fail().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文