Read an unknown number of lines from console in c+

2019-06-23 17:14发布

I am using the following loop to read an unknown number of lines from the console, but it is not working. After I have fed the input I keeping pressing enter but the loop does not stop.

vector<string> file;    
string line;
while(getline(cin,line)
    file.push_back(line);

4条回答
仙女界的扛把子
2楼-- · 2019-06-23 17:21

Try:

vector<string> file;    
string line;
while( getline(cin,line))
{
    if( line.empty())
        break;
    file.push_back(line);
}
查看更多
神经病院院长
3楼-- · 2019-06-23 17:41

Because getline will evaluate to true even if you push only enter.

You need to compare the read string to the empty string and break if true.

vector<string> file;    
string line;
while(getline(cin,line))
{
    if (line.empty())
       break;
    file.push_back(line);
}
查看更多
女痞
4楼-- · 2019-06-23 17:42

For getline is easy, as it is suggested by other answers:

string line;
while(getline(cin,line))
{
    if (line.empty())
       break;
    file.push_back(line);
}

But to cin objects, I found a way to without the need for any breaking character. You have to use the same variable to cin all of the objects. After usage, you need to set it to a default exit value. Then check if your variable is the same after the next cin. Example:

string o;
while(true){
    cin>>o;
    if (o.compare("tmp")==0)
        break;
    // your normal code
    o="tmp";
}
查看更多
兄弟一词,经得起流年.
5楼-- · 2019-06-23 17:45

You should signal the end of file to your application. On Linux it is Ctrl-D, and it might be Ctrl-Z on some Microsoft systems

And your application should test of end of file condition using eof()

查看更多
登录 后发表回答