C++でテキストファイル中の値をプログラムで使用する

C++でのテキストファイル入力を行ったときにファイルの数値をプログラム上の変数に取得する方法です(よくやるけどいつも忘れるので備忘録です)

前提

あるデータ・セット(data.dat)

1 0.1 0.01
2 0.2 0.02
3 0.3 0.03
...

の数値をそれぞれ一行ずつ読んで配列(vector)に入れる

方法

stringstreamを使うと簡単。sstreamヘッダをincludeしてください。

#include <string>
#include <fstream>
#include <sstream>
#include <vector>

using namespace std;
int main(void)
{
	ifstream ifs("data.dat");
	if (ifs.fail()) {
	   cerr << "Cannot open file\n";
	   exit(0);
	}
	string str;
	vector<double> x, y, z;
	double x_temp, y_temp, z_temp;
	while (getline(ifs,str)) {
	      stringstream ss(str);
	      ss >> x_temp >> y_temp >> z_temp;
	      x.push_back(x_temp);
	      y.push_back(y_temp);
	      z.push_back(z_temp);
	}	    		

	return;
}
Shoichiro Masuoka

CNS, the Univ. of Tokyo. Dcotoral student