Search code examples
cscanfc-stringsstrlen

Scanf reads only one word from sentence


I'm new at C and I have a little problem. I need to write a program where the user enters text and the program shows how long it is.

I tried with strlen(), but it's not what I want.

char a[20];
scanf("%s",a)

And if I type "Hello world" the result is 5, but I need 11.

I need to use scanf, but maybe it's impossible to do that with it...


Solution

  • This call

    scanf("%s",a)
    

    fills the character array a until a white space is encountered. So this call will read only the word "Hello" and the input buffer will still keep the second word "world".

    You can use either

    char a[20];
    scanf("%19[^\n]",a );
    size_t n = strlen( s );
    printf( "%zu\n", n );
    

    Here is a demonstrative program

    #include <stdio.h>
    #include <string.h>
    
    int main(void) 
    {
        char a[20] = "";
        
        scanf( "%19[^\n]", a );
        
        size_t n = strlen( a );
        
        printf( "%zu: %s\n", n, a );
        
        return 0;
    }
    

    If to enter

    Hello world
    

    then the output is

    11: Hello world
    

    or

    char a[20];
    
    fgets( a, sizeof( a ), stdin );
    a[strcspn( a, "\n" )] = '\0';
    
    size_t n = strlen( s );
    printf( "%zu\n", n );
    

    Here is a demonstrative program.

    #include <stdio.h>
    #include <string.h>
    
    int main(void) 
    {
        char a[20] = "";
        
        fgets( a, sizeof( a ), stdin );
        a[strcspn( a, "\n" )] = '\0';
        
        size_t n = strlen( a );
        
        printf( "%zu: %s\n", n, a );
        
        return 0;
    }
    

    Again if to enter

    Hello world                               
    

    then the output will be the same as shown above

    11: Hello world