直到用户输入空行为止 [英] reading until user enters blank line

查看:178
本文介绍了直到用户输入空行为止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想从控制台读取行,并将它们放入容器中,直到用户输入空行为止。我不想让这个空行结束在我的容器,虽然。我可以想出五种不同的解决方案:



a)从循环中跳过

  std :: vector< std :: string>容器; 
for(;;)
{
std :: string line = get_input();
if(line.empty())break;
container.push_back(line);
}

b)在循环和循环之前读取

  std :: vector< std :: string>容器; 
std :: string line = get_input();
while(!line.empty())
{
container.push_back(line);
line = get_input();
}

c)作为循环条件的一部分读取,赋值版本

  std :: vector< std :: string>容器; 
std :: string line;
while(!(line = get_input())。empty())
{
container.push_back(line);
}

d)作为循环条件的一部分读取,序列版本

  std :: vector< std :: string>容器; 
std :: string line;
while(line = get_input(),!line.empty())
{
container.push_back(line);
}

e)读过多,在循环后删除

  std :: vector< std :: string>容器; 
std :: string line;
do
{
line = get_input();
container.push_back(line);
}
while(!line.empty());
container.pop_back();

那么,你更喜欢哪种解决方案?

解决方案

我更喜欢(a)。简单和阅读很自然。



(c)重复输入的行。和(d)都使用可能对初学者造成混淆的语法(具体来说,不在中的语句或定义以及条件内的赋值)。我可能更喜欢(c)超过(d)。



(e)是...效率低下。如果最后 push_back 导致重新分配,该怎么办?


Suppose I want to read lines from the console and put those into a container until the user enters a blank line. I do not want that blank line ending up in my container, though. I can think of five different solutions:

a) break from loop

std::vector<std::string> container;
for (; ;)
{
    std::string line = get_input();
    if (line.empty()) break;
    container.push_back(line);
}

b) read before loop and inside loop

std::vector<std::string> container;
std::string line = get_input();
while (!line.empty())
{
    container.push_back(line);
    line = get_input();
}

c) read as part of loop condition, assignment version

std::vector<std::string> container;
std::string line;
while (!(line = get_input()).empty())
{
    container.push_back(line);
}

d) read as part of loop condition, sequence version

std::vector<std::string> container;
std::string line;
while (line = get_input(), !line.empty())
{
    container.push_back(line);
}

e) read too much, remove it after loop

std::vector<std::string> container;
std::string line;
do
{
    line = get_input();
    container.push_back(line);
}
while (!line.empty());
container.pop_back();

So, which solution would you prefer, and why? Which would be the easiest to understand for a beginner?

解决方案

I prefer (a). simple and reads quite naturally.

(b) repeats the line that gets the input.

(c) and (d) both use syntax that may be confusing to beginners (specifically, the comma not within a for statement or a definition, and assignment within a conditional). I'd probably prefer (c) over (d) though.

(e) is... inefficient. What if that last push_back caused a reallocation?

这篇关于直到用户输入空行为止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆