如何在'while(getline(...))'循环中让'string line'与'getline(in,line)'处于同一范围内?
How to have the 'string line' in the same scope as the 'getline(in,line)' in a 'while(getline(...))' loop?
示例:
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,
)。我不明白为什么那个不起作用。有什么想法吗?
你可以作弊一点,只做一个多余的块:
{
std::string line;
while (getline(in, line)) {
}
}
从技术上讲,这不是"相同的范围",但只要外部块中没有其他内容,它就是等效的。
for循环会起作用,我一直这样做:
for (std::string line;
getline(in,line); )
{
}
您可以使用for
循环:
for(std::string line; getline(in, line);) {
}
不过,我认为这不是一个很好的风格。
相关文章:
- Seg Fault Issue C++ (file IO / getline)
- 当用户键入分隔符时,停止getline()输入
- getline() 的原型/库是什么;
- 错误 没有与参数列表匹配的重载函数"getline"实例
- 如何在 c++ 中使用 ',' 作为 getline 分隔符
- 错误:调用'getline'没有匹配函数
- 如何在 c++ 中使用 getline 从文件中读取字符串?
- 将 getline() 与文件一起使用
- 我有三个 getline,但是一旦编译,输入就太多了
- 在 std::getline 和 std::cin 期间卡在循环中
- 为什么 getline() 不读取文本文件中的所有内容?
- 有没有办法在不使用 getline() 的情况下从.csv文件中读取?
- 确切地说,如何解释 std::getline(stream, string) 函数在C++中填充的字符串
- std::getline没有在while循环中重新请求用户输入
- 谁能告诉我我用 getline 做错了什么 (cpp) 格式
- getline repeating same line(c++)(xcode)
- No `while (!my_ifstream.eof()) { getline(my_ifstream, line)
- c++中的is_open()函数总是返回0值,而getLine(myFile, line)不返回任何值
- "Peek ahead"检查下一次对getline(file,line)的调用是否会返回false - 而不实际调用它,即不消耗该行
- 如何在'while(getline(...))'循环中让'string line'与'getline(in,line)'处于同一范围内?