How do I make a string larger than her fgets not move to the next fgets? (C)

Asked

Viewed 41 times

-1

Guys, I got these two string entries:

printf("Entre com a string: ");
fgets(str, sizeof(str), stdin);

printf("\nEntre com o caracter a ser procurado: ");
fgets(caracter, sizeof(caracter), stdin);

It turns out that if I put a larger string in the first entry, it ends up being stored in the second and my program Uga. Has somehow given control of this and make the first entry only store the amount I stipulated?

  • 1

    https://answall.com/a/111702/112052

1 answer

-1

This problem happens because the fgets will read all the characters you ask for except one, because the last will always be a \0, so if you asked him to collect only 10 characters but type:

Input:

abcdefghijklmno[enter]

It will pick up for your string only the abcdefghi\0.

But the problem is with the rest of the input and the enter at the end of it, as it just got played on the keyboard buffer (stdin) as a jklmno[enter] then when the program finds the next data entry using the scanf, this buffer will already be read instantly and already have a enter will already send this data to this input

But as already pointed out in the hkotsubo link in the comments, a very simple solution very commented to balance a problem generated by the overflow protection of fgets, is to use the fflush(stdin); to clean the keyboard buffer, which solves this problem in a simple way, however is not ideal and much less the insurance, so often you will see a larger solution to solve the problem more securely which is the:

int c;
while ( (c = getchar()) != '\n' && c != EOF ) { }

That one while basically will consume your buffer until you find the enter and the End Of File.

Or even this solution that is not portable to other systems:

fseek(stdin, 0, SEEK_END);

They all work partially to mitigate keyboard input problems, if you want to see more to find a safer solution, also linked in the topic of the comment.

  • No, the link I indicated says just the opposite: what to use fflush(stdin) is wrong, because it is an undefined behavior.

  • I’m sorry, I haven’t made so clear the importance of the other methods and the problem of fflush, I imagine I’m more cohesive now

Browser other questions tagged

You are not signed in. Login or sign up in order to post.