简体   繁体   中英

How to check the length of input char array (%s) using scanf() in C

I need to check the length of an input using the function scanf() . I'm using an array of char (%s) to store the input, but I wasn't able to check the length of this input.

this below is the code:

#include <stdio.h>

char chr[] = "";
int n;

void main()
{
    printf("\n");
    printf("Enter a character: ");
    scanf("%s",chr);     
    printf("You entered %s.", chr);
    printf("\n");

    n = sizeof(chr);    
    printf("length n = %d \n", n);
    printf("\n");

}   

it's giving me back that "length n = 1" for the output in each case I've tried.

How can I check the length of the input in this case? Thank You.

to check the length of input char array (%s) using scanf()

  • Do not use the raw "%s" , use a width limit: 1 less than buffer size.

  • Use an adequate sized buffer. char chr[] = ""; is only 1 char .

  • Use strlen() to determine string length when the input does not read null characters .

     char chr[100]; if (scanf("%99s", chr) == 1) { printf("Length: %zu\\n", strlen(chr)); }
  • Pedantic: Use "%n" to store the offset of the scan if code might read null characters (this is rarely or nefariously encountered).

     char chr[100]; int n1, n2; if (scanf(" %n%99s%n", &n1, chr, &n2) == 1) { printf("Length: %d\\n", n2 - n1); }

sizeof is a compile time unary operator which can be used to compute the size of its operand.if you want to calculate the length of the string the you have to use strlen() .like this

#include <stdio.h>
#include <string.h>
  
int main()
{
    char Str[1000];
  
    printf("Enter the String: ");
    if(scanf("%999s", Str) == 1) // limit the number of chars to  sizeof Str - 1
    {                            // and == 1 to check that scanning 1 item worked
        printf("Length of Str is %zu", strlen(Str));
    }
  
    return 0;
}

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