如何拥有“弦线”?在与“getline(in,line)”相同的范围内一会儿(getline(...))”环形?
示例:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以作一点欺骗,只创建一个多余的块:
从技术上讲,这不是“相同的范围”,但只要外部块中没有其他内容,它就是等效的。
You could cheat a little bit and just make a superfluous block:
This isn't technically "the same scope", but as long as there's nothing else in the outer block, it's equivalent.
for 循环就可以了,我一直这样做:
A for loop will work, I do this all the time:
您可以使用
for
循环:不过,我认为这不是很好的风格。
You could use a
for
loop:I don't think this is very good style, though.