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

Time:10-29

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.

CodePudding user response:

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("           
  • Related