简体   繁体   English

fscanf 中的值丢失

[英]Values lossing in fscanf

The IDE I used is Clion.我用的IDE是Clion。 I wanna read the Line-separated data stored in.txt file.我想读取存储在 .txt 文件中的行分隔数据。 Each line contains firstname, surname, gender, ID and age, which are str, str, str, int and int.每行包含名字、姓氏、性别、ID 和年龄,分别为 str、str、str、int 和 int。

StudentList.txt学生名单.txt

Olivia SWANSON F 29001 20
Emma ONEILL F 7900 19

I try to use fscanf to read the data.我尝试使用fscanf来读取数据。

FILE *fp;
char fname[20];
char sname[20];
char gender[1];
int ID;
int age;
fp = fopen("C:\\Users\\Catlover\\Desktop\\DSA\\Program2\\StudentList.txt", "r");
while(fscanf(fp, "%s %s %s %d %d", fname, sname, gender, &ID, &age)!= EOF)
{
    printf("%s,%s,%s,%d,%d\n", fname, sname, gender, ID, age);
}
fclose(fp);
return 0;

But the result it return looks like a little bit weird becasue it doesn't output the second value.但是它返回的结果看起来有点奇怪,因为它不是 output 第二个值。

Result is结果是

Olivia,,F,29001,20
Emma,,F,7900,19

Something shocks me is that the same code runned in PellesC lead to the correct result.令我震惊的是,在 PellesC 中运行相同的代码会导致正确的结果。

I used to learn C++ so there may exists some important rules in C but I didn't notice.我以前学过C++所以C里面可能有一些重要的规则但是我没有注意到。 Can anyone show that for me?谁能给我看一下?

"%s" without width "%s"没有宽度

Never use "%s" in a *scanf() without a width to indicate the max number of non-white-space characters to read and save.切勿在没有宽度的*scanf()中使用"%s"来指示要读取和保存的非空白字符的最大数量。 Recall that after reading, a null character is appended.回想一下,在读取之后,附加了一个null 字符 Example: if the buffer size is 100, code can only read up to 99.示例:如果缓冲区大小为 100,则代码最多只能读取 99。
char gender[1]; is too small for "F" .对于"F"来说太小了。

Wrong check错误检查

fscanf(fp, "%s %s %s %d %d", ...) can return other values than 5 or EOF . fscanf(fp, "%s %s %s %d %d", ...)可以返回5EOF以外的其他值。 As only 5 is acceptable, test against that.因为只有5是可以接受的,所以要针对它进行测试。

Test open success测试开启成功

If fopen() fails, fscanf() , fclose() are bad如果fopen()失败, fscanf()fclose()是坏的

Other issues exist too *其他问题也存在*

But lets use start with fixing the above.但是让我们从修复上述问题开始。


char fname[20 + 1];
char sname[20 + 1];
char gender[1 + 1];
int ID;
int age;
FILE *fp = fopen("C:\\Users\\Catlover\\Desktop\\DSA\\Program2\\StudentList.txt", "r");
if (fp) {
  while(fscanf(fp, "%20s %20s %1s %d %d", fname, sname, gender, &ID, &age) == 5) {
    printf("%s,%s,%s,%d,%d\n", fname, sname, gender, ID, age);
  }
  fclose(fp);
}
return 0;

You need to have space to accommodate null byte also.您还需要有空间来容纳null字节。

char gender[1];

to

char gender[2];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM