【问题标题】:Does getline work inside of a while loop? C++ [closed]getline 在 while 循环内工作吗? C++ [关闭]
【发布时间】:2017-03-29 18:40:06
【问题描述】:

当用户类型退出时它不会因为某种原因而停止?任何想法我做错了什么? C++

vector<string> v;
while(true)
{
    cout << "Enter a string (quit to stop)" << endl;
    getline(cin,names);
    if(names=="quit")break;
    v.push_back(names);
    addFullName(names);
}

void addFullName(string str)
{

    string word = " ";
    int pos = str.find(word);
    string s2;  
    string s3 = str.substr(pos+word.length());
    string s4 = str.substr(pos = 0, pos);
    s2 += s3 + ", " + s4;
    v.push_back(s2);    
}

【问题讨论】:

标签: c++ string vector while-loop


【解决方案1】:

是的,您可以在 while 循环中使用 std::getline。实际上,您可以将其用作 while 循环的哨兵。例如,如果您正在读取文件,则以下内容将读取每一行(并打印)直到 EOF:

std::string line;
std::ifstream fin{"some_file.txt"};

while(std::getline(fin, line)) {
    std::cout << line << '\n';
}

至于你的问题,如果namesstd::string,它应该可以工作。如果不是(即,它是char *),则需要包含缓冲区大小。如果可以的话,请使用std::string

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    • 1970-01-01
    • 2014-03-22
    • 1970-01-01
    • 2016-01-11
    相关资源
    最近更新 更多