C 编程 ScanF 多输入一文件
试图弄清楚如何通过文件读取多个变量。例如,如果我有一个名为“datainput”的文件,其中包含文本行“150”,然后在我的程序中如果我有 int 值,我知道如何读取其中的内容;然后 scanf("%d", &value);当我使用该文件运行程序时,它会读取该文件,然后将其应用于我的变量。但我现在想做的是类似的事情,但读入 2 个值,所以说在我的文本文件中我将有“3.1,3.4”这样的东西,然后将其放在变量 1 和 2 上类似的东西。有人有什么想法吗?
Trying to figure out how to read in multiple variables through a file. for example i know how to read in one, if i have a file called "datainput" which has the line of text "150" and then in my program if I have int value; and then scanf("%d", &value); when i run the program with the file it reads the file and then applies it to my variable. but what I am trying to do now is something similar but instead read in 2 values, so say in my text file i will have "3.1, 3.4" something like this and then put it on variable 1 and 2 something like that. anyone have any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要读取两个值,您所要做的就是在
scanf()
调用中添加一个额外的格式说明符:另外,请注意,如果您正在从文件中读取,则需要使用函数
fscanf
的格式与scanf
类似,只是您需要传递一个指向正在使用的文件的指针:To read in two values all you have to do is add an additional format specifier to the
scanf()
call:Also, just to note if you are reading from a file you need to use the function
fscanf
has a similar format toscanf
except that you need pass a pointer to the file you are working with:如果您的格式是:
尝试:
scanf()
手册页 包含您可以使用的所有格式的完整列表。格式字符串可用于指定输入的格式,就像printf()
可用于指定输出的格式一样(尽管不完全相同)。此处还有一系列简短的示例。
正如评论者指出的那样,如果您正在读取文件,则需要使用
fscanf()
:其中
stream
是您之前使用 < a href="http://www.manpagez.com/man/3/fopen/" rel="nofollow">fopen()
,例如文件。If your format is:
Try:
The
scanf()
man page has a full listing of all the formats you can use. The format string can be used to specify the format of the input much likeprintf()
can be used to specify the format of the output (although not exactly the same).There's also a short series of examples here.
As a commenter points out, if you're reading from a file, you'll need to use
fscanf()
:Where
stream
is something you've previously opened withfopen()
, such as a file.