Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用fscanf读取行_C_Std_Scanf - Fatal编程技术网

使用fscanf读取行

使用fscanf读取行,c,std,scanf,C,Std,Scanf,您好,我有一个包含以下行的文件: wwa weweweof ewewe wdw: 1 11 ms <1 ms <1 ms 174.78.134.1 2 11 ms <1 ms <1 ms 174.78.134.1 3 5 ms <1 ms <1 ms x58trxd00.abcd.edu.com [143.71.290.42] 4 11

您好,我有一个包含以下行的文件:

wwa weweweof ewewe wdw:

      1    11 ms    <1 ms    <1 ms  174.78.134.1  
      2    11 ms    <1 ms    <1 ms  174.78.134.1 
      3     5 ms    <1 ms    <1 ms  x58trxd00.abcd.edu.com [143.71.290.42] 
      4    11 ms    <1 ms    <1 ms  174.78.134.1 

如何检查文件中的行行是否包含8或9个元素,以便可以相应地运行上述else if语句?

使用
fgets
获取行,然后执行一次
sscanf
检查9个元素,如果失败,则再次使用
sscanf
检查8个元素行

如果行的格式相同,除了一个额外的项目,请记住
scanf
函数系列返回成功扫描的项目数。因此,只需调用一次
sscanf
,并检查它是否返回
8
9

使用fscanf读取行

否。

但我觉得这是个好主意因为

否。


使用
fgets()
函数()读取行:

然后,可以使用
sscanf()。(h)值得注意的是,
scanf()
()的返回值不是
EOF
,而是成功读取的实体数。因此,解析字符串的惰性方法可能是:

if (sscanf(buf, "%s %s %s %s %s %s %s %s %s", s1, s2, ...) < 9) {
    // there weren't 9 items to convert, so try to read 8 of them only
}

同样,在扫描字符串时,不应使用运算符的
&
地址-字符数组已衰减为
字符*
,这正是
%s
转换说明符所期望的-
&s1
的类型是
字符(*)[N]
如果
s1
是一个N
char
s的数组,并且不匹配的类型使得
scanf()
调用未定义的行为。

您必须使用
fgets()
函数,因为数组中的
swag
值当前设置为
null

且不使用
字符串
类型(字符数组)数据类型
scanf

scanf("%s",name); //use it without "&" sign
原因:

C中的“字符串”是字符缓冲区的地址。 您希望scanf填充由变量指向的缓冲区中的内存


相反,int是内存块,而不是地址。为了让scanf填满内存,您需要传递它的地址。

谢谢您的解释,但是如果没有9个元素,我应该如何阅读8个元素?如果…@DeepakTivari包含8个转换说明符而不是9,可能是使用了
else吗?然而,我的txt文件可能包含9个元素8或更小的元素,例如:9-我将在第9个元素上获取ip地址并存储它,例如8:我将在第8个元素上获取ip地址并存储它,基本上,重要的是我在8或9号元素上提取ip地址,而不是others@DeepakTivari你不明白我。。。首先尝试转换9个项目。如果失败,那么尝试转换8。等等@DeepakTivari好吧,也许你写的是
s9
,而不是
&s9
?这可能是真的,但你应该解释一下原因。就目前情况而言,这只是一句无益的话。
if (sscanf(buf, "%s %s %s %s %s %s %s %s %s", s1, s2, ...) < 9) {
    // there weren't 9 items to convert, so try to read 8 of them only
}
char s1[100];
sscanf(buf, "%99s", s1);
scanf("%s",name); //use it without "&" sign