C fscanf 奇怪地连接两个字符串
这个程序真的让我很紧张:
我试图从文件中读取一行,其中包含以下信息:
512 MB 136.186.99.1 00-25-B3-0B-31-29
其格式为双字符串字符串
,我正在使用的代码是
fscanf(filePtr, "%lf %s %s %s", &Computer[i].ram, Computer[i].ram_unit, Computer[i].MACNo, Computer[i].IPV4);
但是当我打印 Computer[i].ram_unit
我得到:
MB136.186.99.1
请帮助我找出我做错了什么。如果您希望我粘贴整个代码,请告诉我。
谢谢
This program is really getting on my nerves:
I am trying to read a line from a file with following information:
512 MB 136.186.99.1 00-25-B3-0B-31-29
which is in the format of double string string string
and the code I'm using is
fscanf(filePtr, "%lf %s %s %s", &Computer[i].ram, Computer[i].ram_unit, Computer[i].MACNo, Computer[i].IPV4);
but when I print Computer[i].ram_unit
I get:
MB136.186.99.1
Please help me to find out what I'm doing wrong. Let me know if you like me to paste the entire code.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您在
fscanf
中相对于示例输入颠倒了MACNo
和IPV4
。在没有看到结构定义的情况下无法确定,但看起来可能是数组溢出。例如,如果您的
Computer
定义如下:当您将“MB”读入
ram_unit
时,您最终可能会得到然后当您将IP地址读入IPV4时这使得
当你去打印
ram_unit
时,打印函数将从内存位置&ram_unit[0]
开始并继续打印,直到看到>空。但由于
NULL
最终出现在IPV4[0]
中,并且当您读取 IP 地址时它被覆盖,因此它不会停止打印,直到到达 NULLIPV4[11]
所以你会得到意想不到的串联。First, you have
MACNo
andIPV4
reversed in yourfscanf
relative to the sample input.Can't tell for sure without seeing the structure definition, but it looks like a possible array overrun. For example, if your
Computer
was defined like this:when you read "MB" into
ram_unit
, you could end up havingAnd then when you read in the IP address into IPV4 that makes it
When you go to print out
ram_unit
, the print function will start at the memory location&ram_unit[0]
and keep on printing until it sees aNULL
. But since theNULL
ended up inIPV4[0]
and that got overwritten when you read in the IP address, it won't stop printing until it gets to the NULL atIPV4[11]
and so you get the unexpected concatenation.要从这样的文件中读取一行:
使用此:
To read a line from a file like this one:
Use this: