我想读取一个复数数组(以
a+bi
形式)。我在互联网上找到了一些建议,但是这些方法只能得到real part
,而imaginary part
始终是0
。事实上,下一个数字的 real part
就是前一个数字的 imaginary
。
例如,我有一个文本文件如下:
2+4i
1+5i
7+6i
这是读取复杂数据的建议
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
复数?或者我是否必须将数据作为字符串读取,然后处理该字符串以提取并将其转换回复数?
谢谢!
一种选择是分别读取 2 个
int
中的实部和虚部,并将符号读入 char
,然后将 emplace_back
读入复向量,如
int re, im;
char sign;
while (stream >> re >> sign >> im)
{
vec.emplace_back(re, (sign == '-') ? -im : im);
}
这里
sign
是一个 char
变量,它“吃掉”了符号。
FILE *fp;
char line[80];
int a, b;
if ((fp = fopen("filename", "r") != NULL)
while (fgets(line, 80, fp) != NULL) {
if (sscanf(line, "%d + %di", &a, &b) == 2)
/* do something with a and b */
else
fprintf(stderr, "Not in a+bi form");
}
您的要求(您寻求的输入格式)与您用来阅读的方法不符。复数的默认流是由空格和括号分隔的实部和虚部 - 之间的符号不是强制性的,并且不需要尾部
i
。
解析您寻求的输入的明显方法是读取实部,读取字符,检查该字符是否是带符号的(
+
或-
)并忽略空格,然后读取虚部。这对于 istream
s 来说是微不足道的。
int real[10] = { 0 };
int imaginary[10] = { 0 };
FILE *lpFile = fopen("filename" "rt"); // Open the file
for (int i = 0; i < 10; i++) {
fscanf(lpFile, "%d+%di", &real[i], &imaginary[i]); // Read data 10 times
}
fclose(lpFile); // Close the file
此示例代码将从文件中读取 10 个复数。
// test_input.cpp
#include <complex>
#include <iostream>
int main( void ) {
std::complex<double> a, b;
std::cout << "Enter two complex numbers: ";
std::cin >> a >> b;
std::cout << "a * b = " << a * b << std::endl;
std::cout << "a + b = " << a + b << std::endl;
return 0;
}
g++ -std=c++14 -o test_input test_input.cpp
./test_input
(1,2) (1,-2)
a * b = (5,0)
a + b = (2,0)