C fscanf 输入验证 [英] C fscanf input validation

查看:26
本文介绍了C fscanf 输入验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用带有 fscanf 的 for 循环将文件中的 5 列输入到结构数组中.每个结构有 5 个变量:1 个字符串和 4 个整数,第一个 fscanf 读取字符串名称并将其存储为将其他 4 个输入整数结构化到所述结构中(全部到结构的不同变量).使用正常输入它工作正常.但是当一个字符输入到一个整数列中时,scanf 将 0 和该结构的其余值放入 0 并使用 char 就好像它是一个新结构,即它跳过它后面的所有内容并使用不需要的字符作为名称将行的剩余值作为其输入.我的问题是,是否有一种方法可以忽略由该输入生成的不需要的结构,或者是否可以简单地防止字符被识别而特定的 scanf 被跳过?我曾尝试使用 fgets 而不是 scan 但它没有用,而且我不能使用 0 来整理不需要的值,因为 0 可以作为正常值输入.我理解理想情况下查看代码会有所帮助,但我不想因为剽窃的原因发布它,因为这是为了大学,我不渴望那些剽窃会议.提前致谢,如果问题没有得到很好的解释,我们深表歉意.:)

I am using a for loop with fscanf to input 5 columns from a file into an array of structs.Each struct has 5 variables: 1 string and 4 ints, the first fscanf reads a string name and stores it as part of a struct the other 4 input integers into said struct(all to different variables of the struct). With normal input it works fine. but when a character is input into one of the integer columns the scanf puts 0 for that and the rest of the values of that struct and uses char as if it was a new struct i.e it skips everything after it and uses the unwanted char as name with the remaining values of the row as its input. My question is if there is a way to ignore the unwanted struct generated by that input or a way of simply preventing that the char is recognised and that particular scanf is just skiped? I have tried using fgets instead of scan but it did not work, Also i cannot use the 0 to sort out the unwanted values becuase 0 could be input as a normal value. I understand ideally having a look at the code would be of help but i prefer not to post it for plaigirism reasons as this is for uni and i dont crave those plaigirism meetings. Thanks in advance and sorry if the question is not well explained. :)

推荐答案

关键是输入 5 列",这意味着 文本.使用 fscanf() 同步具有挑战性,尤其是当您想以替代方式解释文本时.最好分开处理读取和解析.

The key is " input 5 columns" which implies a line of text. Using fscanf() is challenging to synchronize with a line, especially if you want to interpret the text in alternate ways. Best to handle reading and parsing separately.

char buf[100];
while (fgets(buf, sizeof buf, istream)) {
  char s[sizeof buf];
  s[0] = 0;
  int i[4] = { 0,0,0,0 }; // default values

  // c is the count of scanned variables
  int c = sscanf(buf, "%s%d%d%d%d", s, &i[0], &i[1], &i[2], &i[3]);

  printf("%d: %s %d %d %d %d\n", c, s, i[0], i[1], i[2], i[3]); 
}

<小时>

" 但是当一个字符输入到整数列之一时,scanf 为该列设置 0 可能是假的.你看到的是之前的值.


" but when a character is input into one of the integer columns the scanf puts 0 for that " is likely false. What you are seeing is the previous value.

这篇关于C fscanf 输入验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆