I'm trying to use scanf
multiple times in a small program to grab inputs that are guaranteed to have spaces. From the multiple threads I've browsed though it seems like scanf("%[^\n]", string);
is the way to get it to ignore spaces. This works, for one line, but any other scanf's after that line don't go through and their respective strings put out the following:
Action: J���J
Resolution: J:F�J�B�J
Here is a bit of example code that I thought would work, but does not.
#include <stdio.h>
int main(void)
{
char str1[100];
char str2[100];
printf("Situation?\n");
scanf("%[^\n]", str1);
printf("Action Taken?\n");
scanf("%[^\n]", str2);
printf("Situation: %s\n",str1);
printf("Action: %s\n",str2);
}
If I input "Just a test" when prompted for the situation the following happens:
Situation?
just a test
Action Taken?
Situation: just a test
Action: ��_��?�J.N=��J�J�d�����J0d���8d��TJ�J
Any suggestions or solutions (excluding fgets
)? An explanation of what's happening would be great as well.
Edit: The solution over at scanf: "%[^\n]" skips the 2nd input but " %[^\n]" does not. why?
Adding in the char* fmt = "%[^\n]%*c";
worked 100%.
char* fmt = "%[^\n]%*c";
printf ("\nEnter str1: ");
scanf (fmt, str1);
printf ("\nstr1 = %s", str1);
printf ("\nEnter str2: ");
scanf (fmt, str2);
printf ("\nstr2 = %s", str2);
printf ("\nEnter str3: ");
scanf (fmt, str3);
printf ("\nstr2 = %s", str3);
printf ("\n");