c++でファイルの内容を配列に入れる方法は何ですか?
ファイルの内容を配列に読み込む方法は以下のステップで行うことができます:
- ファイルを開く:
#include <fstream>
std::ifstream file("filename.txt");
- ファイルが正常に開かれているかを確認してください。
if (!file.is_open()) {
// 文件打开失败
return;
}
- ファイルの内容を保存するための配列を定義します。
const int MAX_SIZE = 100; // 数组的最大大小
int arr[MAX_SIZE];
int count = 0; // 记录数组中元素的个数
- ファイルの内容をループして読み込み、それを配列に格納します。
int num;
while (file >> num) {
arr[count] = num;
count++;
if (count >= MAX_SIZE) {
// 数组已满,无法继续读取
break;
}
}
- ファイルを閉じる
file.close();
コードの完全な例:
#include <iostream>
#include <fstream>
const int MAX_SIZE = 100; // 数组的最大大小
int main() {
std::ifstream file("filename.txt");
if (!file.is_open()) {
std::cout << "文件打开失败" << std::endl;
return 0;
}
int arr[MAX_SIZE];
int count = 0;
int num;
while (file >> num) {
arr[count] = num;
count++;
if (count >= MAX_SIZE) {
std::cout << "数组已满,无法继续读取" << std::endl;
break;
}
}
file.close();
// 打印数组中的内容
for (int i = 0; i < count; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
return 0;
}
実際のファイル名に “filename.txt” を置き換え、同じディレクトリにそのファイルを作成してください。