I'm trying to read user input and store it as a string including the whitespace. I did a search for a solution and was pointed to fgets() or scanf(%[^\n], str). But both these solutions give me an error.
This is what I have:
//MAX_CHARACTERS is set to 30
scanf("%d", &input);
if (input == 1){
int pr;
char na[MAX_CHARACTERS+1];
printf("\nEnter the name: ");
scanf("%[^\t\n]", &na);
while (strlen(na)>MAX_CHARACTERS){
printf("\nName is too long, enter new name: ");
scanf("%[^\t\n]", &na);
}// end na check
printf("\nEnter priority: ");
scanf("%d", &pr);
while (pr>MAX_PRIORITY || pr <MIN_PRIORITY){
printf("\nBad priority, enter new priority (0-100): ");
scanf("%d", &pr);
}//end pr check
It works fine if I use %s
in all instances of %[^\t\n]
but when I use %[^\t\n]
or
fgets(na, 30, stdin)
, it skips the first scanf for name and goes straight to "Enter priority: ". Then when I print, I have a blank name with whatever priority I entered.
EDIT: Sorry, the missing quotes on the first scanf is a typo. Not a cause of the problem. I typed in '1' for the first scanf("%d", input).
FIXED IT
Since it won't let me post an answer yet,
Someone figured it out. Incase anyone's still interested, the problem was the first scanf().
scanf("%d", &input);
It is leaving a \n in the buffer. The second one is taking the \n and reading it as an input so it gets skipped.
SOLUTION:
Putting a
fflush(stdin); //right after the if statement seems to have fixed the issue.
Thanks for everyone's help.
&input
one)?1ENTER
or1corilENTER
? :) – Grosswardeinscanf
very well, but for reading a string your argument should be achar*
, i.e. eitherna
or&na[0]
. But I don't see a%s
format specifier anywhere. – Sophisterfflush(stdin);
is not the solution. The behavior offflush()
on an input stream is undefined. If you've left characters in the input buffer, you need to read them. A more general solution is to usefgets()
to read a line of text into a string, thensscanf()
on the string to extract data from it. (sscanf()
has potential problems with numeric input, but we can leave that for later.) – Ungerscanf()
orsscanf()
. (Think about what(scanf("%d", &input);
will do if the input isn't a number.) – Unger