I agree with the others that scanf()
is probably not the right tool here.
Another way could be to use fgets()
and strchr()
and a pointer as in
char str[100], *ptr;
while( (fgets(str, sizeof(str), stdin))!=NULL ){
if( (ptr=strchr(str, '\n'))!=NULL )
{
*ptr=0;
}
if( (ptr=strchr(str, ' '))!=NULL )
{
*ptr=0;
ptr++;
if( strchr(ptr, ' ')==NULL )
{
printf("\nTwo words: %s, %s", str, ptr);
}
else
{
printf("\nMore than two words!");
}
}
else//only one word
{
printf("\nOne word: %s", str);
}
}
fgets()
is used to read in the input into a character array str
. fgets()
returns NULL
on error.
Since fgets()
also reads in any trailing \n
, we check the string for \n
if it's there, it's replaced with a \0
to denote end of string in the
if( (ptr=strchr(str, '\n'))!=NULL )
{
*ptr=0;
}
part.
strchr()
returns NULL
if the searched character is not present in the string.
strchr()
is again used to check for a space in str
. If none is found, only one word was read and otherwise multiple words were input.
If more than one word is there, the space is replaced with a \0
using the pointer returned by strchr()
so that doing a
printf("%s", str);
will now print only the first word and the pointer is incremented so that it now points to the beginning of the second word. This is done in
if( (ptr=strchr(str, ' '))!=NULL )
{
*ptr=0;
ptr++;
Now, strchr()
is once again used to check for another case in which case more than two words were input. Otherwise only two words were input and the second word is output using
printf("%s", ptr);
You could use a similar approach to read more words.