gpt4 book ai didi

c - 具有意外无限循环的文件

转载 作者:行者123 更新时间:2023-11-30 14:57:35 24 4
gpt4 key购买 nike

我使用结构来创建复数,并且该函数给出了求和的结果。完成此操作后,我尝试使用文件将数据存储在complextoplam.txt中。在“r”模式下,我将数据存储在complextoplam中。 txt 为“w”模式,数据为

  10.000000 5.000000i
8.000000 9.000000i
Sum=18.000000+14.000000i

将数据存储在文本文件中后,我想读取数据并在控制台屏幕中打印,但这部分出现错误。当我使用 fscanf 和 EOF 进行 while 循环时,循环尚未完成,并且将进入无限循环。为什么我的程序会这样。我认为你的想法会改善我。亲切的问候。

#pragma warning (disable :4996)
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
#include <ctype.h>
#include <string.h>
struct Complex {
double real;
double img;
};
struct Complex c1, c2,c3;
void Toplam(struct Complex c1, struct Complex c2)
{
c3;
c3.img = c1.img + c2.img;
c3.real = c1.real + c2.real;
}

int main() {

/*c1, c2;
printf("Write complex c1.\n");
scanf("%lf %lf", &c1.real, &c1.img);
printf("Write complex c2.\n");
scanf("%lf %lf", &c2.real, &c2.img);
Toplam(c1, c2);
printf("Sum=%lf + %lfi", c3.real, c3.img);*/
//this part is used for only in "w" mode//
int i;
FILE *kp;
kp = fopen("complextoplam.txt", "r");
if (kp == NULL)
{
printf("File opening error.\n");
system("pause");
exit(1);
}
printf("File opened correctfully.\n");
while (fscanf(kp,"%lf %lf\n %lf %lf \n%lf %lf\n", &c1.real, &c1.img,
&c2.real, &c2.img,&c3.real, &c3.img) != EOF)
{
printf("%lf %lf %lf %lf %lf %lf", c1.real, c1.img, c2.real, c2.img,
c3.real, c3.img);
}
getch();
return 0;
}

最佳答案

fscanf 调用中的格式字符串与文件的格式不匹配。因此,fscanf 将返回正确读取的值的数量,而不是 EOF

为了解决此问题,请将格式字符串更改为以下内容:"%lf %lfi\n%lf %lfi\nSum=%lf+%lfi"

关于c - 具有意外无限循环的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43834871/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com