C++でファイル読み込み
よりC++らしいファイルの読み込み方法はなんだろうか. C++の教科書などを見てもファイル入出力になると途端にfprintf, fscanfが登場することがあって困る.
出力に関してはboost::formatなどを含め, fprintf無しでもfstreamでできるが, 入力となるとfscanfの代替をどのように実現すればよいのか困る.
下記サイトには以下のような方法が指摘されていたが, 結局scanfを使っているのよね.
http://d.hatena.ne.jp/nagardjunas/20110524/1306231384
ifstream ifs("data.txt"); string str; if (ifs.fail()) { cerr << "File not found.\n"; exit(0); } int a(0), b(0), c(0); while (getline(ifs, str)) { sscanf(str.data(), "%d,%d,%d", &a, &b, &c); const int sum(a + b + c); cout << a << " + " << b << " + " << c << " = " << sum << endl; }
"getline(ifs, str)"は"ifs >> str"でも良いっぽい. 見た目がすごく気持ち悪いけどw