如何从文件中读取多行
How do I read multiple lines from a file?
我正在编写一个从命令行获取输入文件的函数。输入文件如下所示:
11 25
1 2 3 4 5 6 7 8
1 2 3
1 3 5
1 2 2
我想将第一行上的两个数字存储在整数变量中。第二行存储在数组中。第三行和后续行存储在另一个容器中。目前我有一个可以从第一行读取的程序:
void classFunctions::storeInput(const char* inputFile)
{
std::ifstream file(inputFile);
std::string placeholderString;
while(!file.eof())
{
while(std::getline(file, placeholderString))
{
//Do something
}
}
}
但是我将如何更改它,以便它可以从第二、第三和后续行读取?
检查文本文件是否为空后,您应该调用getline()
两次并继续阅读直到eof()
getline(file, first_line);
//proceed to process with a stringstream
getline(file, second_line);
//process
while(true) {
string line;
getline(file, line);
//process
if(file.eof()) break;
}
第一行只是对两个变量的提取。对于第二行,应该使用 std::getline()
,您可能应该使用它std::istringstream
并使用 std::istream_iterator
将行解析为数组。其余线路也需要连续调用std::getline()
。
相关文章:
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 读取文件的最后一行并输入到链接列表时出错
- 为什么在读取文件大小时文件IO速度会发生变化
- 读取文件时运行时的未知行为
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- C++ 读取文件读取文件不正确
- 读取文件并将其存储在unordered_map中时出现问题
- 读取文件时无法使用 OpenMP 获得加速
- 使用istringstearm和get行缓慢读取文件
- 如何继续读取不同功能中的文件,而不是从头开始再次读取文件?
- 读取文件时引发异常
- 从标准输入读取文件后读取用户输入
- 在读取文件后重置句柄
- 如何在C++编译时读取文件?
- std::ifstream 在读取文件中最后一项时设置 eofbit,但仅在读取数值类型时发生
- 读取文件在第二次调用时返回INVALID_HANDLE
- 通过指针读取文件
- 逐行读取文件,并将数据插入变量和数组中