Scanf reads only one word from sentence

Viewed 556

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...

4 Answers

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

%s is the correct specifier for strings:

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

However %s stops on spaces. If you want to read spaces as well you should do:

scanf("%[^\n]", a);

scanf() is used for only one word. It takes a word when it see an white space character(space,new line) and the end. You should again use scanf() to take another word. You can use fgets() to take a line. But don't forget to read how to use fgets() function.

Also, you must use an adress to store with scanf.

int a;
scanf("%d",&a);

But you don't need it for char arrays because a char array's name is address.

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