c++11 - Read complex numbers (a+bi) from text file in C++ -
i want read array of complex numbers (in a+bi form). there several suggestions found on internet, methods result real part, while imaginary part 0. , infact real part of next number imaginary of previous number.
for example, have text file follow:
2+4i 1+5i 7+6i and here suggestion reading complex data
int nrow = 3; std::complex<int> c; std::ifstream fin("test.txt"); std::string line; std::vector<std::complex<int> > vec; vec.reserve(nrow); while (std::getline(fin, line)) { std::stringstream stream(line); while (stream >> c) { vec.push_back(c); } } (int = 0; < nrow; i++){ cout << vec[i].real() << "\t" << vec[i].imag() << endl; } while (1); return 0; and output result is:
2 0 4 0 1 0 is there proper way read a+bi complex numbers text file? or have read data string, , process string extract , convert complex numer?
thanks !
one option read separately real , imaginary part in 2 ints, , sign char, emplace_back complex vector, like
int re, im; char sign; while (stream >> re >> sign >> im) { vec.emplace_back(re, (sign == '-') ? -im : im); } here sign char variable "eats" sign.
Comments
Post a Comment