multiple word string input through scanf( )
what was the syntax to input strings with more than one word i.e with space in between through scanf() not gets()
Solution 1:
Is it
scanf("%[^\t\n]",string);
Solution 2:
char name[50];
printf("Enter your full name: ");
scanf("%[^\n]",name);
The %[^\n]
conversion asks scanf( )
to keep receiving characters into name[ ]
until a \n
is encountered. It's a character-set, and starting with ^
means accept anything but that.
See https://en.cppreference.com/w/c/io/fscanf for details on how scanf works.
Solution 3:
Better to used fgets()
than scanf()
for reading a line of user input.
If code must use scanf()
then
char buf[100];
// Read up to 99 char and then 1 \n
int count = scanf("%99[^\n]%*1[\n]", buf);
if (count == EOF) {
Handle_EndOfFile(); // or IO error
}
if (count == 0) { // Input began with \n, so read and toss it
scanf("%*c");
}
Now parse buf
for individual words.