具有意外无限循环的文件

时间:2017-05-07 18:02:09

标签: c file

我使用了结构来创建复数,函数给出了求和的结果。在这之后,我尝试在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;
}

1 个答案:

答案 0 :(得分:1)

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

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