没有输入任何内容时结束循环 [英] Ending a loop when nothing is entered
问题描述
通常,我编写一个控制循环,如下所示:输入的循环将int写入向量nVec中,直到输入"done"为止.
Usually I write a control loop as follows: Loop that enters writes ints into vector nVec until "done" is entered.
while (cin >> sString){
if (sString="done")
{
break;
}
nVec.push_back(sString);
}
这可以很好地工作,但是如果我希望在用户没有输入任何内容(仅按Enter键)时结束循环,我该怎么做?
this works fine, but how would I go about doing this if I wanted the loop to end once the user entered nothing (just pressed enter)?
推荐答案
您不能不输入任何内容"进行令牌提取.停止循环的唯一方法是让用户发送文件结尾(在Linux上为Ctrl-D).我个人会说这是正确的行为,但是如果您想以空输入结尾,则需要阅读以下行:
You can't "not enter anything" into your token-wise extraction. The only way for your loop to stop is for the user to send end-of-file (Ctrl-D on Linux). I would personally say that this is the correct behaviour, but if you want to end on empty input, you need to read lines:
Sales_item total;
for (std::string line; std::getline(std::cin, line); )
{
if (line.empty()) { exit_program(); /* or "break" */ }
std::istringstream iss(line);
for (Sales_item book; iss >> book; )
{
total += book;
std::cout << "The current total is " << total << std::endl;
}
}
这样,您可以将每一行标记成可能的多本书.如果您只想每行一本书,请跳过内循环,然后说 std :: istringstream(line)>>书;
.
This way, you tokenize each line into possibly multiple books. If you just want one book per line, rip out the inner loop and just say std::istringstream(line) >> book;
.
这篇关于没有输入任何内容时结束循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!