C++ File to Array: Read Files into Arrays
In C++, you can store files in an array variable by first reading the file contents and then saving them in the array. Here is an example code:
#include <iostream>
#include <fstream>
#include <vector>
int main() {
std::ifstream file("example.txt");
std::string line;
std::vector<std::string> lines;
if (file.is_open()) {
while (std::getline(file, line)) {
lines.push_back(line);
}
file.close();
// 将文件内容存储到数组中
for (const auto& l : lines) {
std::cout << l << std::endl;
}
} else {
std::cout << "Unable to open file" << std::endl;
}
return 0;
}
The code example above opens a file named “example.txt”, reads its contents, and stores each line in a vector. Finally, it prints out the file content. Feel free to modify the code to suit your needs.