Using 2 scanf(“%[^n]s”) but the second one is getting skipped

Solution for Using 2 scanf(“%[^n]s”) but the second one is getting skipped
is Given Below:

int main(){

     char str1[20], str2[20];
    printf("Enter string 1 : ");
    scanf("%[^n]s",str1);

    printf("Enter string 2 : ");
    scanf("%[^n]s",str2);

    printf("String 1 is %sn",str1);
    printf("String 2 is %sn",str2);
    removeFromSecond(str1,str2);
}

The output is :

Enter string 1 : in

Enter string 2 : String 1 is in

String 2 is ■   a

It’s just not asking to enter the second string.
I can’t remember, but I’ve read somewhere that there is a line we need to add to eat up all unused ‘n’s.
Please, if anyone knows that, I need exactly that line.

2nd scanf("%[^n]s",str2); fails to save anything as the previous line’s 'n' was not consumed by the prior scanf("%[^n]s",str1); nor this scanf("%[^n]s",str2);.

To read a line of user input use fgets().

// scanf("%[^n]s",str1);
fgets(str1, sizeof str1, stdin);

As fgets() also reads and saves a potential 'n', use below to lop it off if it is there.

str1[strcspn(str1, "n")] = 0;

scanf() is rarely as good choice. Do not use until you understand why it is bad.


If you _must use scanf(), drop the useless s in the format, add a width:

// Ugly POS code
char str1[20] = "";  // Set to empty string in case nothing saved
// Read up to 19 non-n characters.  If more available, read them but don't save.
scanf("%19[^n]%*[^n]",str1);  
// consume up to 1 trailing n, do not save.
scanf("%*1[n]");

// TBD check return values.

Well, use fgets() as everyone is telling me to because it is the right choice. But still if anyone wants to know the answer for what I actually asked, it is as weather-vane said in comments It’s a rookie’s mistake, just add a space before the % in the second scanf.

Like scanf(“%[^n]”, str2); -> to -> scanf(” %[^n]”, str2);