Reputation: 33
#include <stdio.h>
int main()
{
char name[100];
int i;
for (i=0; i<3;i++){
printf("\nEnter the name : ");
scanf("%[^\n]",name);
}
printf ("\nName of Student : %s ",name);
}
I want this code to ask for the name 3 times however it only does so once, any help is appreciated.
Upvotes: 0
Views: 4551
Reputation: 3326
#include <stdio.h>
int main()
{
char name[100];
int i;
for (i=0; i<3;i++){
printf("\nEnter the name : ");
scanf ("%[^\n]%*c", name);
}
printf ("\nName of Student : %s ",name);
}
The [] is the scanset character. [^\n] tells that while the input is not a newline ('\n') take input. Then with the %*c it reads the newline character from the input buffer.
you can also use:
scanf(" %[^\n]s",name);
Upvotes: 2
Reputation: 206667
When you use:
scanf("%[^\n]",name);
the newline character is left in the input stream. When the function is called the second and third time, scanf
reads zero characters into the receiving argument.
Add a line to read and discard the newline character after that line.
getc();
Upvotes: 0