我正在为学校写一本成绩簿计划,我对一件事感到困惑。 我们有一个要读取的文件,其中包含多个学生ID和多个分数。 会这样做:
results = fscanf(gradebook, "%d %d %d %d", id, sco1, sco2, sco3);
在读取时将数字存储到那些变量中,然后在变量用完时将光标停止以存储信息?…然后我应该直接进入计算函数来计算最终成绩,然后再将fscanf循环到fscanf中下一个学生?
results = fscanf(gradebook, "%d %d %d %d", id, sco1, sco2, sco3); getCalc(sco1, sco2, sco3);
这是允许的吗? 谢谢您的帮助。
以下是一个工作示例,给出每个学生ID的平均成绩:
#include int main(void) { int id, sco1, sco2, sco3; while (fscanf(stdin, "%d%d%d%d", &id, &sco1, &sco2, &sco3) == 4) { printf("%d: %gn", id, (sco1+sco2+(double)sco3)/3.0); } return 0; }
会这样做:
results = fscanf(gradebook,“%d%d%d%d”,id,sco1,sco2,sco3);
在读取时将数字存储到那些变量中,然后在用完变量以存储信息时停止光标?
不,除非它处于while循环中,否则在读取四个条目ONCE后它会完全停止,除非您使用results
的值来控制while循环并多次调用fscanf()以在每次调用时扫描4个条目。
例:-
//Keeps reading unless it encounters less than 4 parameters, which might be the case //if an end of file is reached, or your data pattern changes. while( fscanf(gradebook, "%d %d %d %d", id, sco1, sco2, sco3) == 4 ) { //You can pass the data of individual id, to calculate function, and compute the required //sum, total or other data locally in the function, there is really no reason to use pass //address in your case, so just transfer data using pass by value method. getCalc(id,sco1,sco2,sco3); }
回答你的第一个和第二个问题: id
的类型, sco1
, sco2
和sco3
应该是int *
(也就是指向 int
的指针 ),这些变量应该明确指向实际的int
对象,你应该检查返回值( results
)使用它们之前。 例如:
int a, b, c, d; int *id = &a, *sco1 = &b, *sco2 = &c, *sco3 = &d; int results = fscanf(gradebook, "%d %d %d %d", id, sco1, sco2, sco3); if (results == 4) { getCalc(sco1, sco2, sco3); }
此外,getCalc应该接受int *
类型的参数。 满足所有这些要求后,第三个问题的答案是:是的,您可以使用sco1
, sco2
和sco3
作为参数调用getCalc
。
您可能已经猜到了,这里不需要中间指针变量,这可以简化。 但是,这种简化需要修改fscanf
表达式(插入&addressof
运算符):
int id, sco1, sco2, sco3; int results = fscanf(gradebook, "%d %d %d %d", &id, &sco1, &sco2, &sco3); if (results == 4) { getCalc(&sco1, &sco2, &sco3); }
你正在读哪本书?
以上就是c/c++开发分享停止fscanf?相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/522163.html