如何拥有“弦线”?在与“getline(in,line)”相同的范围内一会儿(getline(...))”环形?

发布于 2024-11-14 06:44:22 字数 766 浏览 4 评论 0原文

示例:

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 statements-3 类型(不考虑重载的operator,)。我不明白为什么那个不起作用。有什么想法吗?

Example:

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 loops won't work for the first iteration:

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

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

Of course one can always have a if(line.empty()) getline(...) but that doesn't really feel right.
I also thought of abusing the comma operator:

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

but that won't work, and MSVC tells me that's because line isn't convertible to bool. Normally, the following sequence

statement-1, statement-2, statement-3

should be of type type-of statement-3 (not taking overloaded operator, into account). I don't understand why that one doesn't work. Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

巴黎夜雨 2024-11-21 06:44:22

您可以作一点欺骗,只创建一个多余的块:

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

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

You could cheat a little bit and just make a superfluous block:

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

This isn't technically "the same scope", but as long as there's nothing else in the outer block, it's equivalent.

谢绝鈎搭 2024-11-21 06:44:22

for 循环就可以了,我一直这样做:

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

A for loop will work, I do this all the time:

for (std::string line;
     getline(in,line); )
{
}
几度春秋 2024-11-21 06:44:22

您可以使用 for 循环:

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

}

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

You could use a for loop:

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

}

I don't think this is very good style, though.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文