我试图从我的c程序中的文本文件中读取一些数据,但得到了垃圾值。
下面是文件中的输入格式

3442
Tack Hammer
9
3.550000
ABC317

这是我读取此文件数据的代码
char name[100];
int product_code;

fscanf(fin, "%d", &x[i].product_code); //taking id from file is fine
printf("\n%d\n",x[i].product_code); // works correctly

fscanf(fin,"%[^\n]",name);
printf("Data from file:\n%s",name);  // it displays junk values

这里是输出预览
有人能纠正我吗。谢谢您

最佳答案

让我们看看代码。

char name[100];

创建100字节长的char数组它未初始化并包含“垃圾”。
fscanf(fin, "%d", &x[i].product_code);

3442扫描fin
printf("\n%d\n",x[i].product_code);

打印换行符、上述fscanf扫描的号码和换行符线路
fscanf(fin,"%[^\n]",name);

是什么导致了这个问题下一个要读取的字符是\n,一个换行符。如果下一个字符是a%[^\n],则\n将失败因此,fscanf失败并返回零。
printf("Data from file:\n%s",name);

打印Data from file、换行符和name包含的“垃圾”。
怎么解决这个问题?
在第一个getc(fin);之后使用fscanf来读取并丢弃\n字符。

关于c - 从文件读取字符串时获取垃圾值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29677089/

10-12 12:49
查看更多