如何在getline中使用stringstream构造函数? [英] How to use stringstream constructor in getline?

查看:460
本文介绍了如何在getline中使用stringstream构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

继续 http://stackoverflow.com/a/1120224/390066



为什么我不能使用

  getline(stringstream ){} 

而不是

  stringstream lineStream(line); 
getline(lineStream,cell,','){}



更新



我应该澄清一下我想在循环中使用getline。 p>

此外,我还应该注意到,我最初的目的是使用getline逐行读取文件,并使用新的getline中的行, ',',这是更直观的imo。



从我到目前为止的理解,getline不是为此设计,因为它需要一个非const输入并给出const令牌;因此,getline不能盲目递归。

解决方案

如@James Kanze所示。



问题是你真的想要吗?

该流在表达式结尾处被销毁,因此您只能从中读取一个单元格。



如果我们在上下文中查看此内容的原始问题

ie不能在循环中使用:

  std :: string line = / * Init * /; 
std :: stringstream lineStream(line);

std :: string cell;
while(std :: getline(lineStream,cell,','))
{
//使用单元格做事情。
}

如果将代码放在此上下文中,将无法正常工作: / p>

  std :: string cell; 
while(std :: getline(std :: istringstream(line).flush(),cell,','))
{
//
}


$ b while()将每次完全评估。所以你进入一个infinte循环读取第一个单元格不断。


Following up http://stackoverflow.com/a/1120224/390066.

Why can't I use

getline(stringstream(line),cell,','){}

instead of

stringstream lineStream(line); 
getline(lineStream,cell,','){}

?

update

I should have clarified that I want to use getline within a loop.

Furthermore, I should have also noted that my initial intention was to read a file line-by-line using getline and use the line from that in the new getline that would divide on ',', which is more intuitive imo.

From what I understood so far, getline is not designed for that because it takes a non-const input and gives const token; therefore, getline cannot be blindly recursed.

解决方案

As show by @James Kanze you can.

The question is do you really want to?
The stream is destroyed at the end of the expression so you are only reading one cell from it.

If we look at this in the context of the original question:
i.e. You can not use that in a loop:

std::string       line = /* Init */;
std::stringstream lineStream(line); 

std::string cell;
while(std::getline(lineStream, cell, ','))
{
    // Do stuff with cell.
}

If you place your code into this context it will not work as expected:

std::string cell;
while(std::getline(std::istringstream(line).flush(), cell, ','))
{
    // Do stuff with cell.
}

As the expression inside the while() will be fully evaluated each time. So you go into an infinte loop reading the first cell continuously.

这篇关于如何在getline中使用stringstream构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆