2

例子:

std::ifstream in("some_file.txt");
std::string line; // must be outside ?
while(getline(in,line)){
  // how to make 'line' only available inside of 'while' ?
}

Do-while 循环不适用于第一次迭代:

std::ifstream in("some_fule.txt");

do{
  std::string line;
  // line will be empty on first iteration
}while(getline(in,line));

当然,一个人总是可以有一个if(line.empty()) getline(...),但这并不真正感觉对。我还想过滥用逗号运算符:

while(string line, getline(in,line)){
}

但这不起作用,MSVC 告诉我这是因为line不能转换为 bool。通常,以下顺序

statement-1, statement-2, statement-3

应该是类型type-of statement-3(不考虑重载operator,)。我不明白为什么那个不起作用。有任何想法吗?

4

3 回答 3

6

你可以稍微作弊,然后做一个多余的块:

{
    std::string line;
    while (getline(in, line)) {
    }
}

这在技术上不是“相同的范围”,但只要外部块中没有其他内容,它就是等价的。

于 2011-06-06T02:00:52.923 回答
3

for 循环会起作用,我一直这样做:

for (std::string line;
     getline(in,line); )
{
}
于 2011-06-06T02:17:26.910 回答
2

你可以使用一个for循环:

for(std::string line; getline(in, line);) {

}

不过,我认为这不是很好的风格。

于 2011-06-06T02:18:52.823 回答