如何将 scanf() 与 fopen 一起使用

发布于 2024-07-05 16:47:59 字数 510 浏览 5 评论 0原文

我正在编写一个程序,但在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

朦胧时间 2024-07-12 16:47:59

我认为你想要 fscanf 而不是 scanf

I think you want fscanf not scanf.

徒留西风 2024-07-12 16:47:59

您的代码看起来应该使用 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).

几味少女 2024-07-12 16:47:59

怎么样:

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/

一世旳自豪 2024-07-12 16:47:59

您使用了错误的功能。 您应该使用fscanf

You're using the wrong function. You should be using fscanf.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文