逐行读取文件
Read from a file line by line
如何逐行从文本文件中读取,然后使用相同的数组保存它们..
首先,您似乎在代码中使用了using namespace std;
。这是非常不鼓励的。这是我如何使用std::vector
.首先,您必须导入<vector>
头文件。
std::ifstream in_file("file.txt");
if (!in_file) { ... } // handle the error of file not existing
std::vector<std::string> vec;
std::string str;
// insert each line into vec
while (std::getline(in_file, str)) {
vec.push_back(str);
}
std::ifstream
的 .close()
方法是在其析构函数中处理的,所以我们不需要包含它。这更干净,读起来更像英语,而且没有神奇的常数。另外,它使用 std::vector
,这是非常有效的。
编辑:修改,每个元素都带有std::string[]
:
std::ifstream in_file("file.txt");
if (!in_file) { ... } // handle the error of file not existing
std::vector<std::string[]> vec;
std::string str;
// insert each line into vec
while (std::getline(in_file, str)) {
std::string array[1];
array[0] = str;
vec.push_back(array);
}
对 getline 的引用表示数据附加到字符串中
Each extracted character is appended to the string as if its member push_back was called.
尝试在读取后重置字符串
编辑
每次调用 getline 时,line 都会保留旧内容并在末尾添加新数据。
line = "";
将在每次读取之间重置数据
相关文章:
- 正在将csv文件读取为双精度矢量
- 将从格式化文本文件读取的文本数据存储到链表
- C++ 读取文件读取文件不正确
- 使用对象文件读取三角形数据网格
- 如何减慢从 BVH 文件读取的 opengl 动画?
- 从文件读取,并写入函数C++中的数组
- 从对象C++中的文件读取内容时出现分段错误
- 从文件读取并通过矢量输出到控制台
- 尝试将字符串从文件读取到无符号字符向量中
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 简化文件读取的函数
- 如何将逗号分隔的文件读取为 2D int 数组?
- 在 c++ 中将数据从文件读取到队列中
- 'std::wstring_convert'尽可能多地转换(从 UTF8 文件读取块)
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 文件读取C++包括空格键
- 从文件读取时未将值推回矢量
- 从文件 C++ 读取时的无限循环
- 从同一文件读取和写入?
- 从.txt文件读取到C++中的双精度向量