您必须将指针传递给fscanf()
:
fscanf(file,"%d, %d", &y[xy], &x[xy]);
此外,由于x
和y
是 的向量double
,因此您需要使用%lf
来读取值。您还应该检查返回值fscanf()
以确保成功读取了两个值:
if (fscanf(file, "%lf, %lf", &x[xy], &y[xy]) != 2)
...handle error...
您需要打开编译警告并修复编译器警告的内容 - 或者获得一个更好的编译器来为您提供此类警告(g++ -Wall
如果您使用 G++,这是一个好的开始)。
Note, too, that this curious code reads a line into line
, then reads some numbers direct from the file. Did you mean to write:
if (sscanf(line, "%lf, %lf", &x[xy], &y[xy]) != 2)
...handle error...
What you've got will have fgets()
read the first line (assuming nothing longer than 1 KiB), then the fscanf()
will read the first two numbers on a line, and the next iteration of fgets()
will read the residue of the line, leaving fscanf()
to find the numbers on the next line. Unusual, but a feasible scheme.
In a comment, you say that the format on each line is x
taby
; if that's the case and there is no comma separating the values, then you need to remove the comma from the format string:
if (sscanf(line, "%lf %lf", &x[xy], &y[xy]) != 2)
...handle error...
However, if your crash really is happening in the while
line, then your problem is almost certainly that the file failed to open. Always check the return from fopen()
(or any other file-opening function). You can fail to open a file for many, many reasons and blundering on assuming that the file opened when it didn't never leads to happiness.
Also, in C++, it is a good idea to initialize variables as you define them:
FILE *file = fopen("ecg.txt", "r");
if (file == 0)
...handle error...
QVector<double> x(1000), y(1000);
char line[1024];
int xy = 0;