【问题标题】:How to have the 'string line' in the same scope as the 'getline(in,line)' in a 'while(getline(...))' loop?如何在“while(getline(...))”循环中将“字符串行”与“getline(in,line)”置于相同的范围内?
【发布时间】:2011-09-08 23:37:06
【问题描述】:

例子:

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 不能转换为布尔值。通常,以下顺序

statement-1, statement-2, statement-3

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

【问题讨论】:

  • 您似乎对getline() 的任一版本的工作方式存在根本性的误解。我建议查看cplusplus.com/reference/string/getline - 它不会返回布尔值。
  • @Brian:看来你有误会。 :) getline 返回传入的流对象,它可以隐式转换为void*void* 可以隐式转换为bool。或者在 C++0x 中,流对象将在诸如 ifwhile 等布尔上下文中直接隐式转换为 bool。
  • 我不明白。为什么 for 循环版本不起作用? line 在第一次迭代时不会为空。在进入循环之前执行条件语句。
  • @Benjamin:啊!那是听别人说话而不测试自己的结果。 :

标签: c++ scope while-loop getline


【解决方案1】:

您可以使用for 循环:

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

}

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

【讨论】:

  • 我看不出这种风格有什么问题。但我更喜欢 while 循环(但这只是一种品味)。
【解决方案2】:

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

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

【讨论】:

  • 谢谢你提醒我不要相信别人,除非你自己测试过...... :)
【解决方案3】:

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

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

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

【讨论】:

  • 是的,这将是最后的手段。 :P
  • 这个解决方案还不错。这段代码可能应该被移动到一个单独的函数(称为 ProcessLines 或其他东西)。模块化就是胜利!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-29
  • 2017-03-29
  • 1970-01-01
  • 2014-11-22
  • 1970-01-01
  • 2019-08-09
  • 1970-01-01
相关资源
最近更新 更多