How can a user input space in scanf();?
This is how we use scanf() if the user will enter just a word:
scanf(“%s”, &var1);
But what if the user enters an input with space, lets say a name “This S. Me”, this will only show the first word “This”, so how can we let the program read spaces?
Its actually simple, all you have to do is add this code “[0-9a-zA-Z. ]” so it will look just like this:
scanf(“%20[0-9a-zA-Z. ]s”, &name);
where:
20 is the array size.
[0-9a-zA-Z. ] this will let the program accept characters that range from, numbers 0-9, small letters of the alphabet, big letters of the alphabet , the character period “.” and lastly the space ” “.
s is the data type, since we are entering a string we used %s.
&name is the variable used to store the data from the user.
There you have it, now you can enter space in C.
Here is a short sample program to make things more clear.
This program is made from Microsoft Visual Visual Studio C++ 6.0
#include<stdio.h>
main()
{
char name[20];
printf(“Enter your name: “);
scanf(“%20[0-9a-zA-Z. ]s”, &name);
printf(“Your Name is: %s\n”, name);
}
Leave a comment