fscanf return 字符串的值
fscanf return value for a string
对编码还是个新手,我对这个真的很困惑。我搜索了 fscanf returns 成功分配的字符数,那么为什么下面的代码 return 是 1 而不是 4?
string temp;
int len;
len = fscanf(fp, "%[^-,]s", temp);
printf("\n%s", temp);
printf("\nlen: %d", len);
temp[len] = '[=11=]';
输出:
2020
len: 1
I searched up that fscanf returns the number of successfully assigned characters
没有。 fscanf()
returns 成功分配的 输入项数 .
来自fscanf(3)
的documentation,
RETURN VALUE
Upon successful completion, these functions shall return the
number of successfully matched and assigned input items; this
number can be zero in the event of an early matching failure.
所以,记住len = fscanf(...)
不是return正确初始化的字符长度,而是成功分配的输入项的数量。在这种情况下,它是 1,这是正确的。
len = fscanf(fp, "%[^-,]s", temp);
排除集 %[^-,]
的 format specifier 不需要或包含尾随 s
.
fscanf
的 return 值是分配的项目数,而不是字符数。
另外,temp[len] = '[=16=]';
这里是错误的,大体上是多余的。
下面展示了如何正确解析第一个 -,
分隔标记,进行全面错误检查并使用 %n
检索实际消耗的字符数。
#include <stdio.h>
int main()
{
const char str[] = "2021-02-12";
char tok[79 + 1]; // `%79s` or similar to prevent buffer overrun
int len; // number of characters actually parsed
int cnt = sscanf(str, "%79[^-,]%n", tok, &len); // number of items matched and assigned
if(cnt != 1)
{ printf("error reading token\n"); return 1; }
printf("input: \"%s\"\n", str);
printf("items: %d\n", cnt);
printf("chars: %d\n", len);
printf("token: \"%s\"\n", tok);
printf("remaining: \"%s\"\n", str + len);
return 0;
}
input: "2021-02-12"
items: 1
chars: 4
token: "2021"
remaining: "-02-12"
对编码还是个新手,我对这个真的很困惑。我搜索了 fscanf returns 成功分配的字符数,那么为什么下面的代码 return 是 1 而不是 4?
string temp;
int len;
len = fscanf(fp, "%[^-,]s", temp);
printf("\n%s", temp);
printf("\nlen: %d", len);
temp[len] = '[=11=]';
输出:
2020
len: 1
I searched up that fscanf returns the number of successfully assigned characters
没有。 fscanf()
returns 成功分配的 输入项数 .
来自fscanf(3)
的documentation,
RETURN VALUE
Upon successful completion, these functions shall return the number of successfully matched and assigned input items; this number can be zero in the event of an early matching failure.
所以,记住len = fscanf(...)
不是return正确初始化的字符长度,而是成功分配的输入项的数量。在这种情况下,它是 1,这是正确的。
len = fscanf(fp, "%[^-,]s", temp);
排除集
%[^-,]
的 format specifier 不需要或包含尾随s
.fscanf
的 return 值是分配的项目数,而不是字符数。另外,
temp[len] = '[=16=]';
这里是错误的,大体上是多余的。
下面展示了如何正确解析第一个 -,
分隔标记,进行全面错误检查并使用 %n
检索实际消耗的字符数。
#include <stdio.h>
int main()
{
const char str[] = "2021-02-12";
char tok[79 + 1]; // `%79s` or similar to prevent buffer overrun
int len; // number of characters actually parsed
int cnt = sscanf(str, "%79[^-,]%n", tok, &len); // number of items matched and assigned
if(cnt != 1)
{ printf("error reading token\n"); return 1; }
printf("input: \"%s\"\n", str);
printf("items: %d\n", cnt);
printf("chars: %d\n", len);
printf("token: \"%s\"\n", tok);
printf("remaining: \"%s\"\n", str + len);
return 0;
}
input: "2021-02-12"
items: 1
chars: 4
token: "2021"
remaining: "-02-12"