Space acts as null character


#include <stdio.h>
#include <string.h>

int main(){

int aux;
char name[20];
char hello[8] = "Hello, "; 

printf("Introduce your name: ");
scanf("%s", name); 
printf("%s %s", hello, name); 
printf("\nYour name starts with %c\n", name[0]); 

aux = strlen(name);
printf("The size of the char is %d", aux);

return 0;


When running this program, if you enter a single name it works fine, but as soon as you put a compound name (or in general you enter a space on the screen), the program only shows you up to the space. I am using the Dev C ++ compiler. In fact with "strlen" it tells you that the new size of the string is the amount of characters that you have put before the space. Any idea what is happening?


Any idea what is happening?

What has to happen happens. scanf stops reading a character string when it encounters a separator. And what is a separator? Some examples:

  • Reach end of EOF input buffer
  • Line break: '\n' , '\r'
  • Tab: '\t'
  • Space: ' '

Thus, by virtue of the 4th scanf , scanf stops reading when it encounters a space. Which is just what is happening to you.

Solutions? To have them there are … you can use getline :

size_t max_length = sizeof(name); // max_length = 20
getline(&name, &max_length, stdin);

Unlike scanf , getline will read all characters until it reaches a newline or the end of the input buffer.

Scroll to Top