string - Issues ignoring spaces with scanf when using multiple scanf's in C -
i'm trying use scanf multiple times in small program grab inputs guaranteed have spaces. multiple threads i've browsed though seems scanf(%[^\n]",string); way ignore spaces. works, 1 line, other scanf's after line don't go through , respective strings put out following:
action: j���j resolution: j:f�j�b�j here bit of example code thought work, 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 input "just test" when prompted situation following happens:
situation? test action taken? situation: test action: ��_��?�j.n=��j�j�d�����j0d���8d��tj�j any suggestions or solutions (excluding fget)? explanation of what's happening great well.
edit: solution on @ scanf: "%[^\n]" skips 2nd input " %[^\n]" not. why?
adding in 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");
change
scanf("%[^\n]", str1); to
scanf("%[^\n]%*c", str1);//consume newline @ end of line
Comments
Post a Comment