简体   繁体   中英

How to get string length using scanf function

How to get the string length without using strlen function or counters, like:

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

Input: abcde

Expected output: 5

You can use assignment-suppression (character * ) and %n which will store the number of characters consumed into an int value:

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

Explanation:

%*s will parse a string (up to the first whitespace characters) but will not store it because of the * . Then %n will store the numbers of characters consumed (which is the length of the string parsed) into count .

Please note that %n is not necessarily counted for the return value of scanf() :

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.

quoted from the man page where you will find everything else about scanf() too.

Use the %n format specifier to get the amount of characters consumed so far and write it to len of type int :

char buf[50];
int len;

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

printf("%d", len);

You can doing this with the n specifier:

%n returns the number of characters read so far.

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

Explanation : Here [] is used as scanset character and ^\\n takes input with spaces until the new line encountered. For length calculation of whole string, We can use a flag character in C where nothing is expected from %n , instead, the number of characters consumed thus far from the input is stored through the next pointer, which must be a pointer to int. This is not a conversion, although it can be suppressed with the *flag . Here load the variable pointed by the corresponding argument with a value equal to the number of characters that have been scanned by scanf() before the occurrence of %n .

By using this technique, We can speed up our program at runtime instead of using strlen() or loop of O(n) count.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM