ファイルのデータを入力(読み込み)/iostream・fstream
スポンサーリンク
スポンサーリンク
ライフスタイル関連のコンテンツ
お金 | 仕事 | 勉強 | プライベート | 健康 | 心
プログラミング関連のコンテンツ
C言語/C++入門 | Ruby入門 | Python入門 | プログラミング全般
お金 | 仕事 | 勉強 | プライベート | 健康 | 心
プログラミング関連のコンテンツ
C言語/C++入門 | Ruby入門 | Python入門 | プログラミング全般
C++のファイルI/O(入出力)は、入出力に使用するiostreamクラスを利用します。
#include
スポンサーリンク
ディスクファイルへのI/Oを実行するには、std::ifstream、std::ofstream、std::fstreamクラスを用い、インクルードファイル
まずは、読み込みようのファイルを用意します。
numbers.dat
12 34 56 345 45677 7867 11 456
プログラム本体。
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <assert.h>
int main() {
const int DATA_SIZE = 8; // データ数
int data_array[DATA_SIZE]; // データ
std::ifstream data_file("numbers.dat"); // 入力ファイル
int i;
if (data_file.fail()) {
std::cerr << "Error: Could not open\n";
exit (8);
}
for (i = 0; i < DATA_SIZE; ++i) {
assert(i >= 0);
assert(i < static_cast<int>(sizeof(data_array)/sizeof(data_array[0])));
data_file >> data_array[i];
}
int total; // 数値の合計
total = 0;
for (i = 0; i < DATA_SIZE; ++i) {
assert(i >= 0);
assert(i < static_cast<int>(sizeof(data_array)/sizeof(data_array[0])));
std::cout << data_array[i] << "\n";
total += data_array[i];
}
std::cout << "\nTotal of all the number is " << total << "\n";
return 0;
}
「data_file >> data_array[i];」と>>演算子を用いることで、配列に格納されたファイル中の数字を一つずつ読み込んでいます。
実行結果。
12 34 56 345 45677 7867 11 456 Total of all the number is 54458
スポンサーリンク
>> 次の記事 : 変換ルーチン・I/O変換フラグ
- - 関連記事 -
- std::printf・std::scanf/Cの出力・入力関数
- CのI/Oライブラリ・ファイル読み取りと書き込み
- readとwrite・バッファを使用しないI/O
- バッファを使用しないI/O
- バイナリデータ・バイナリファイルのI/O
- ASCIIコードの実験
- 出力ファイル・オープンフラグ
- 変換ルーチン・I/O変換フラグ
スポンサーリンク