Number of language questions

Asked 2 years ago, Updated 2 years ago, 31 views

char str[2000];
scanf("%[^\n]", str);
printf("%s", str);

char str1[2001];
fgets(str1, sizeof(str1), stdin);
printf("%s", str1);

Enter the string first in the code above.

After the string is stored in the str buffer

I wrote the above code to get the string back into the str1 buffer with the fgets function

Str1 buffer also has a string in str.

I think it's related to the stream fflust(stdin) does not work. How do I solve this? ㅠ<

c

2022-09-22 19:58

1 Answers

When you receive input from scanf, the buffer stores the following:

Pass the string to (entered string)\n" and str and leave only open characters in the buffer.

fgets will only hand over str1.

So the second output would be an open letter.

If you want to receive a new input, it would be better to write the code as follows.

char str[2000];
scanf("%[^\n]", str);
printf("%s", str);

getchar(); // Clears the opening character of the buffer

char str1[2001];
fgets(str1, sizeof(str1), stdin);
printf("%s", str1);


2022-09-22 19:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.