有多行的getline(cin,input)?(C++)

ass*_*tor 2 c++ getline

我在这里遇到一个让我很难过的问题.所以,我必须阅读格式的内容[请阅读正文,以便更好地理解我的问题]:

               TITLE

The text is actually from a file being redirected 
to input stream via piping in linux bash. I cannot
use ifstream or anything other than some form of cin,
of which I believe getline to be the most useful. 

etc.
Run Code Online (Sandbox Code Playgroud)

具体来说,给我带来困难的是TITLE和身体之间的空白.我似乎无法想办法解决使用getline(cin,string)的方法.

我提出的最好的:

while(inputString.size() != 0)
    getline(cin,inputString);
    //process string
Run Code Online (Sandbox Code Playgroud)

......用上面提到的空行抛出窗外.

伙计们,有什么想法?

谢谢!

Eit*_*n T 5

我认为这里的真正问题是你的逻辑.您的输入包含空行和非空行,因此如果要读取所有行,则不应该依赖行的长度.这可以通过测试返回的流来完成std::getline,如下所示:

while (getline(cin, inputString))
{
    // Do something with inputString...
}
Run Code Online (Sandbox Code Playgroud)

循环cin逐行读取,并在到达输入结束时停止.

  • @assignment_operator`std :: getline`不仅修改了要读取的流对象,还返回它.正如[here](http://stackoverflow.com/a/11063495/1336150)所述,可以通过将流对象转换为`void*`指针(或者自C++以来的显式`bool`)来测试流对象的有效性. 11).当出现读取错误时,您将获得零值("false"),*例如*流中没有更多数据. (2认同)