我正在尝试从文本文件中提取两列数字。第一列是数字的实部,第二列是虚部。我设法从文件中提取数字列表作为字符串,但我不知道如何将字符串分成两部分。我曾尝试使用 sscanf 功能,但没有奏效。困难的部分是数字可以是正数和负数,因此我不能在 strtok 函数的分隔符中使用 + 和 - 因为它会删除负数。我被困了几天,所以任何建议都将不胜感激。提前致谢。这是我写的在 sscanf 行出错的代码。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <complex.h>
char array[35]= "[[[1+1i -4+100i 45-234i -56-78i]]]";
char *arrayp[35];
int count,n,i,j;
double complex z1;
double real = 0;
double imaginary = 0;
int main()
{
arrayp[0] = strtok(array," []");
n=1;
while (arrayp[n-1]!=NULL)
{
arrayp[n] = strtok(NULL, " []");
n++;
}
// up to this point it has been tested to work. the remaining code is very
// sloppy since I have tried 8 different things and have quickly written one of
// the options tried.
for(j=0;j<n;j++)
{
if (strchr(*arrayp, '+'))
{
sscanf(arrayp[j],"%f+%fi", real, imaginary);
}
else if(arrayp string has equal to more than 1 '-')
{
sscanf(arrayp[j],"%f%fi", real, imaginary);
}
}
}
输出应该是这样的:
0 0
-4 100
45 -234
-56 -78
我注意到尝试在 strchr 中搜索 *arrayp 时出现错误,但它是一个指针,我不知道如何将指针转换为字符串,因此我可以将其放入此文件中。感谢您提前提供的帮助和努力。