Read an unknown number of lines from console in c++

北战南征 提交于 2019-12-14 03:52:44

问题


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);

回答1:


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);
}



回答2:


Try:

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



回答3:


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()




回答4:


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";
}


来源:https://stackoverflow.com/questions/7980985/read-an-unknown-number-of-lines-from-console-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!