C 中的 fscanf - 如何确定逗号?
我正在通过 fscanf() 从文件中读取一组数字,对于每个数字我想将其放入数组中。问题是这些数字是用“,”分隔的,如何确定 fscanf 应该读取多个密码,并且当它在文件中找到“,”时,它会将其保存为整数?谢谢
I am reading set of numbers from file by fscanf(), for each number I want to put it into array. Problem is that thoose numbers are separated by "," how to determine that fscanf should read several ciphers and when it find "," in file, it would save it as a whole number? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这可能是一个开始:
使用这个输入文件:
...输出是这样的:
你到底想做什么?
This could be a start:
With this input file:
...the output is this:
What exactly do you want to do?
我可能会使用类似的东西:
%d 转换数字,“%*[, \t\n]” 读取(但不分配)任何连续的分隔符 - 我将其定义为逗号,空格、制表符、换行符,尽管更改为您认为合适的任何内容相当简单。
I'd probably use something like:
The %d converts a number, and the "%*[, \t\n]" reads (but does not assign) any consecutive run of separators -- which I've defined as commas, spaces, tabs, newlines, though that's fairly trivial to change to whatever you see fit.
fscanf(file, "%d,%d,%d,%d", &n1, &n2, &n3, &n4);
但如果存在则不起作用数字之间的空格。 这个答案展示了如何做到这一点(因为有不是为此的库函数)fscanf(file, "%d,%d,%d,%d", &n1, &n2, &n3, &n4);
but won't work if there are spaces between numbers. This answer shows how to do it (since there aren't library functions for this)Jerry Coffin 的回答很好,但有一些注意事项需要注意:
fscanf 在文件末尾返回一个(负)值,因此循环不会正确终止。
i
也会递增,因此它最终会指向数据末尾后面的 1。此外,如果格式参数之间留有空格,fscanf 还会跳过所有空格(包括
\t
和\n
。我会选择这样的东西,
或者如果你想强制在格式参数之间有一个逗号 。您可以将格式字符串替换为
"%d , "
。Jerry Coffin's answer is nice, though there are a couple of caveats to watch for:
fscanf returns a (negative) value at the end of the file, so the loop won't terminate properly.
i
is incremented even when nothing was read, so it will end up pointing one past the end of the data.Also, fscanf skips all whitespace (including
\t
and\n
if you leave a space between format parameters.I'd go for something like this.
Or if you want to enforce there being a comma between the numbers you can replace the format string with
"%d , "
.