如何将 scanf() 与 fopen 一起使用
我正在编写一个程序,但在使用 scanf 和 fopen 协同工作时遇到问题。
据我所知,我的错误行似乎是:
FiLE * DataFile
DataFile = fopen("StcWx.txt","r");
scanf(DataFile, "%i %i %i %.2f %i %i", &Year, &Month, &Day, &Precip, &High, &Low);
它打开的文件有一个天气数据列表,如下所示:(
1944 4 12 0 58 24
1944 4 13 0.4 58 29
1944 4 14 0.54 42 29
1944 4 15 0 43 27
那些空格是制表符)
显示的错误是“[警告]传递 `scanf 的 arg 1 '来自不兼容的指针类型“
有人可以帮助我吗?
I'm writing a program and am having trouble using the scanf and fopen working together.
From what I can tell my erroneous lines seems to be:
FiLE * DataFile
DataFile = fopen("StcWx.txt","r");
scanf(DataFile, "%i %i %i %.2f %i %i", &Year, &Month, &Day, &Precip, &High, &Low);
The file it opens from has a list of weather data that looks like this:
1944 4 12 0 58 24
1944 4 13 0.4 58 29
1944 4 14 0.54 42 29
1944 4 15 0 43 27
(Those spaces are tabs)
The error that is displayed is "[Warning] passing arg 1 of `scanf' from incompatible pointer type"
Can anyone help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为你想要 fscanf 而不是 scanf。
I think you want fscanf not scanf.
您的代码看起来应该使用 fscanf,而不是 scanf。
我强烈建议使用 fgets 和 sscanf 而不是直接调用 fscanf。
fscanf 可能会失败,从而使您不确定文件指针的位置。 使用 fgets 获取整行并使用 sscanf 扫描字符串意味着您始终知道文件指针的状态,并且很容易备份到行的开头(字符串仍在内存中)。
Your code looks like it should be using fscanf, not scanf.
I would strongly suggest using fgets and sscanf rather than directly calling fscanf.
The fscanf can fail in ways that leave in doubt where your file pointer is. Using fgets to get whole lines and sscanf to scan the strings means you always know the state of the file pointer and it's very easy to back up to the start of the line (the string is still in memory).
怎么样:
freopen ("StcWx.txt","r",stdin);
scanf("%i %i %i %.2f %i %i", &年份, &月、&日、&降水、&高点、&低点);
http://www.cplusplus.com/reference/cstdio/freopen/
How about:
freopen ("StcWx.txt","r",stdin);
scanf("%i %i %i %.2f %i %i", &Year, &Month, &Day, &Precip, &High, &Low);
http://www.cplusplus.com/reference/cstdio/freopen/
您使用了错误的功能。 您应该使用
fscanf
。You're using the wrong function. You should be using
fscanf
.