不读取每行文本文件

时间:2012-12-08 03:30:05

标签: c

我正在尝试编写一个从文本文档中读取一行的程序,并将该语言方程打印成数学方程式,但由于某种原因,它只读取TXT文件的第二行和最后一行。

文字示例

subtraction,3,57
multiplication,90,46
division,26,7
division,26,0

代码

int main()
{
  char name[21], namecopy[21];
  char *nc, com = 100;
  int num1, num2, p, i;
  FILE *file;

  file = fopen("C:\\hw10.txt", "r");
  strcpy(namecopy, name);

  while (fgets (namecopy,21,file)!=NULL)
  {
    fscanf(file, "%[^,]%*c %i%*c %i%*c", &name, &num1, &num2);
    printf("%s %i %i\n", name, num1, num2);     

    if( strcmp( name, "subtraction" ) == 0 )
    {
      p = num1-num2;
      printf("%d - %d = %i \n", num1, num2, p);
    }

    if( strcmp( name, "addition" ) == 0 )
    {
      p = num1+num2;
      printf("%d + %d = %i \n", num1, num2, p);
    }

    if( strcmp( name, "multiplication" ) == 0 )
    {
      p = num1*num2;
      printf("%d x %d = %i \n", num1, num2, p);
    }

    if( strcmp( name, "division" ) == 0 )
    {
      if(num2==0)
         printf("undefiend\n");
      else
      {
        p = num1/num2;
        printf("%d / %d = %i \n", num1, num2, p);
      }
    }
  }
  char ch=getchar();
  return 0;
}

1 个答案:

答案 0 :(得分:1)

这一行:

fscanf(file, "%[^,]%*c %i%*c %i%*c", &name, &num1, &num2);

应该是

sscanf(namecopy, "%[^,]%*c %i%*c %i%*c", &name, &num1, &num2);