C++从txt文件中读取getline并存储到字符串数组中的方法如下:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
int main() {
std::ifstream file("example.txt"); // 打开txt文件
std::vector<std::string> lines; // 创建字符串数组
if (file.is_open()) {
std::string line;
while (std::getline(file, line)) { // 逐行读取文件内容
lines.push_back(line); // 将每行内容存储到字符串数组中
}
file.close(); // 关闭文件
} else {
std::cout << "无法打开文件" << std::endl;
return 1;
}
// 打印存储的字符串数组内容
for (const auto& line : lines) {
std::cout << line << std::endl;
}
return 0;
}
上述代码首先使用std::ifstream
打开名为"example.txt"的txt文件。然后,创建一个std::vector<std::string>
类型的字符串数组lines
来存储文件中的每一行内容。
接下来,通过file.is_open()
检查文件是否成功打开。如果成功打开,使用std::getline()
逐行读取文件内容,并将每行内容存储到字符串数组lines
中。
最后,使用一个循环遍历打印存储的字符串数组内容。
这是一个简单的示例,你可以根据实际需求进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云