gpt4 book ai didi

c - 不读取文本文件的每一行

转载 作者:太空宇宙 更新时间:2023-11-04 03:58:53 24 4
gpt4 key购买 nike

我正在尝试编写一个程序,从文本文档中读取一行并将口头方程式打印成数学方程式,但由于某种原因,它只读取 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;
}

最佳答案

这一行:

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

应该是

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

关于c - 不读取文本文件的每一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13774164/

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