通过输入空行退出循环

Exit loop by entering blank line

本文关键字:退出 循环 输入      更新时间:2023-10-16

即使输入空行,循环也不中断。

string temp;
cin >> temp;
while (!temp.empty()) {
    cout<<"Hello"<<endl;
    cin>>temp;
}

当我没有输入而只按enter时,它应该退出循环。

尝试break命令continue将跳过循环的当前迭代

当没有字符可以从input stream中读取时,cin抛出flag failbit,并且永远不会继续尝试从input stream中读取extract字符。你可以通过getline( cin, temp )实现你的目标。getline()读取到stream中的deliminating character,然后丢弃它,即使stream中没有其他字符,留下temp为空,并从temp.empty()返回0

string temp;
getline( cin, temp );
while (!temp.empty()) {
    cout<<"Hello"<<endl;
    getline( cin, temp );
}
http://www.cplusplus.com/reference/istream/istream/operator-free/