如何使用scanf函数获取字符串长度

How to get string length using scanf function

如何在不使用 strlen 函数或计数器的情况下获取字符串长度,例如:

scanf("???",&len);
printf("%d",len);

输入: abcde

预期输出: 5

您可以使用 n 说明符执行此操作:

%n returns the number of characters read so far.

char str[20];
int len;
scanf("%s%n", &str, &len);

使用 %n 格式说明符获取到目前为止消耗的字符数并将其写入 len 类型 int:

char buf[50];
int len;

if ( scanf("%49s%n", buf, &len) != 1 )
{
     // error routine.
}

printf("%d", len);

您可以使用assignment-suppression(字符*)和%n,它将消耗的字符数存储到一个int值中:

 int count;
 scanf( "%*s%n", &count );
 printf( "string length: %d\n", count );

解释:

%*s 将解析字符串(直到第一个空白字符)但不会存储它,因为 *。 然后 %n 将消耗的字符数(即解析的字符串长度)存储到 count.

请注意,%n 不一定计入 scanf() 的 return 值:

The C standard says: "Execution of a %n directive does not increment the assignment count returned at the completion of execution" but the Corrigendum seems to contradict this. Probably it is wise not to make any assumptions on the effect of %n conversions on the return value.

引自 the man page,您也可以在其中找到关于 scanf() 的所有其他内容。

解释:这里[]用作scanset字符^\n 接受带空格的输入 直到遇到新行。对于整个字符串的长度计算,我们可以在 C 中使用 标志字符 ,其中 %n 没有任何期望,而是消耗的字符数因此far from input是通过next指针存储的,它必须是一个指向int的指针。这不是转换,尽管它可以用 *flag 抑制。这里加载相应参数指向的变量,其值等于 %n.

出现之前 scanf() 扫描的字符数

通过使用这种技术,我们可以在运行时加速我们的程序,而不是使用 strlen() 或 O(n) 计数的循环。

scanf("%[^\n]%n",str,&len);
printf("%s %i",str,len);