月曜日, 4月 02, 2007

[C++] (ファイルから)数値データを読み込む

老化の進んだねこさんの備忘録シリーズ…しばらくすると覚えてられない orz

#include <iostream> #include <cstdlib> #include <vector> #include <string> #include <boost/regex.hpp> #include <boost/lexical_cast.hpp> struct Spectrum { double freq, power; }; int main(int argc, char* argv[]) { std::istream& is = std::cin; std::string line; boost::regex reg("^\\s*(\\S+)\\s*(\\S+)\\s*"); boost::smatch results; std::vector<Spectrum> spec; while (!is.eof()) { std::getline(is,line); Spectrum sp; if (boost::regex_search(line,results,reg)) { try { sp.freq = boost::lexical_cast<double>(results.str(1)); sp.power = boost::lexical_cast<double>(results.str(2)); } catch (boost::bad_lexical_cast &) { // do anything.... } spec.push_back(sp); } } std::vector<Spectrum>::iterator it; for (it=spec.begin();it!=spec.end();++it) { std::cout << it->freq << " " << it->power << std::endl; } return EXIT_SUCCESS; }コンパイルはこんな感じ g++ -O3 -o spec spec.cc -lboost_regex-gcc-mt-1_32(参考)

0 件のコメント: