電子書籍の厳選無料作品が豊富!

c++でファイルから複素数を読み込みたいのですが、方法が思いつきません。
ファイルには以下のような形式で複素数が書かれているとします。
------------------------------------------------------------------------
(1.23,2.34) (2.34,3.45) (3.45,4.56)
(4.56,5.67) (5.67,6.78) (6.78, 7.89)
・・・・・
------------------------------------------------------------------------
かっこの左側が実部で右側が虚部で、1つのかっこが1つの複素数をあらわしています。

このファイルを読み込んで、複素数のvector(vector<complex<double> >)をつくりたいです。
簡単なソース、または考え方をおしえていただけると助かります。

A 回答 (2件)

できた(Visual C++ 2012)。



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

int main( ) {
using namespace std;

vector<vector<complex<double>>> matrix;
ifstream file("complex.txt");
string line;
while ( getline(file,line) ) {
istringstream stream(line);
complex<double> c;
vector<complex<double>> row;
while ( stream >> c ) {
row.push_back(c);
}
matrix.push_back(row);
}

// 結果確認
for ( auto& row : matrix ) {
for ( auto& item : row ) {
cout << item << " ";
}
cout << endl;
}
}
    • good
    • 0
この回答へのお礼

ありがとうございます。

お礼日時:2013/02/13 22:35

#include <complex>


#include <iostream>
#include <fstream>

int main( ) {
using namespace std;

complex <double> c;
ifstream stream("complex.txt");
while ( stream >> c ) {
cout << c << endl;
}
}

/* 実行結果(Visual C++ 2012)
(1.23,2.34)
(2.34,3.45)
(3.45,4.56)
(4.56,5.67)
(5.67,6.78)
(6.78,7.89)
*/
> このファイルを読み込んで、複素数のvector(vector<complex<double> >)をつくりたいです。

getlineで一行ずつ読み、上記と同様。

この回答への補足

回答ありがとうございます。質問をまちがえてしまいました。1行目をvector<complex<double> > v1に入れ、2行目をvector<complex<double> > v2に入れるにはどうしたらよいでしょうか?

補足日時:2013/02/13 22:32
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!