从C ++中的文本文件中读取复数(a + bi) [英] Read complex numbers (a+bi) from text file in C++

查看:1439
本文介绍了从C ++中的文本文件中读取复数(a + bi)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取一个复数数组(在 a + bi 表单中)。有几个建议,我发现在互联网上,但这些方法只导致实部分,而虚部是总是 0 。而且,下一个数字的实数部分是上一个数字的虚数

i want to read an array of complex numbers (in a+bi form). There are several suggestions I found on the internet, however those methods only result the real part, while the imaginary part is always 0. And infact the real part of the next number is the imaginary of the previous number.

例如,我有一个文本文件如下:

For example, I have an text file as follow:

2+4i
1+5i
7+6i

这里是建议读取复杂数据



And here is a suggestion for 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);
    }
}

for (int i = 0; i < nRow; i++){
    cout << vec[i].real() << "\t" << vec[i].imag() << endl;
}

while (1);
return 0;

输出结果是:

2   0
4   0
1   0

是否有正确的方法从文本文件中读取 a + bi 复数?或者,我必须以字符串形式读取数据,然后处理字符串以提取并将其转换回复数数字。

Is there a proper way to read a+bi complex numbers from text file? Or do I have to read the data as a string, and then process the string to extract and convert it back to complex numer?

谢谢!

推荐答案

一个选项是分别读取2 int 中的实部和虚部,在复合向量中签入 char ,然后 emplace_back ,例如

One option is to read separately the real and imaginary part in 2 ints, and the sign into a char, then emplace_back into the complex vector, like

int re, im;
char sign;
while (stream >> re >> sign >> im)
{
    vec.emplace_back(re, (sign == '-') ? -im : im);
}

这里符号用于吃掉符号的 char 变量。

Here sign is a char variable that "eats" up the sign.

这篇关于从C ++中的文本文件中读取复数(a + bi)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆