Using scanf
with the %c
conversion format specifier will only read a single character.
In order to read a whole word, you can use the %s
specifier instead. However, in the English langauge, it is possible for a first name to consist of several words, such as John Paul. In that case, "Paul" is not a middle name, but part of the first name. With the input "John Paul"
, scanf
would only read "John"
from the input stream and leave " Paul"
on the input stream. This would probably be undesirable.
For this reason, it would probably be better to read and store a whole line of input, instead of only a single word. Although this is also possible with scanf
, I recommend to use the function fgets
instead.
When reading in a string consisting of several characters, you must provide a pointer to a memory location that has sufficient allocated space for storing the string. Providing a pointer to a single char
is not sufficient, as such a memory location is only able to store a single character. This means that the memory location is only able to store an empty string consisting only of a null terminating character.
One simple way of allocating sufficient space for storing a string is to declare a char
array. When passing such an array to a function, the array will automatically decay to a pointer to the first element of the array.
Here is an example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main( void )
{
char first_name[200];
//prompt user for input
printf( "Enter your name: " );
//read one line of input
if ( fgets( first_name, sizeof first_name, stdin ) == NULL )
{
fprintf( stderr, "Input error!\n" );
exit( EXIT_FAILURE );
}
//remove newline character from the input, if it exists,
//by overwriting it with a null terminating character
first_name[strcspn(first_name,"\n")] = '\0';
//print back input to user
printf( "Hello, %s.\n", first_name );
}
This program has the following behavior:
Enter your name: John Paul
Hello, John Paul.