gpt4 book ai didi

c++ - 逐行读取文件

转载 作者:行者123 更新时间:2023-11-28 02:37:42 25 4
gpt4 key购买 nike

我如何逐行读取文本文件,然后使用相同的数组来保存它们..

最佳答案

首先,您似乎正在使用 using namespace std;在你的代码中。 This is highly discouraged.这是我将如何使用 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);
}

关于c++ - 逐行读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26953360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com