C++でfileを配列に入れる方法は何ですか?
C++でファイルを配列変数に入れることができますが、ファイルの内容を先に読み取り、その内容を配列に格納する必要があります。以下にサンプルコードを示します。
#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;
}
上記のコード例は、”example.txt”というファイルを開き、その中身を読み取り、各行をベクターに保存します。 最後にファイルの内容を出力します。 必要に応じて、コードを変更してファイルの内容を処理できます。