Search code examples
cscanffgets

fgets() / scanf() do-while loop


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{

    char strA[10];

    int i, j;


    do {

        j = 0;

        memset(&strA,'\0', sizeof(strA));

        printf("Please enter your password: ");
        fgets (strA,10,stdin);

        printf("\n%s\n\n",strA);

        if (strlen(strA) > 8) {
            printf("That password is too long\n");
        }
        else {
            j++;
        }

    } while (j<1);
return 0;
}

Hello. I am running fgets() inside a dowhile loop. I first test to see if an inputted string is too long, and then prompt to enter the string again if the string is too long (by letting the dowhile start over). The problem is that the carry over from a string that is too long (the extra characters that get cut from fgets() being set to 10) gets inputted in the second, third, and so on iteration of the dowhile loop until eventually the remainder of the string satisfies the else statement, and the dowhile terminates. I need each iteration of the dowhile loop to be a fresh start where a string is manually entered. Can anyone help?

replace:

fgets (strA,10,stdin);

with:

scanf("%10s", strA);

same problem.


Solution

  • Try this

    fgets (strA,10,stdin);
    int c;                      // Notice that I declared c as int (getchar() returns int)
    while((c = getchar()) != '\n' && c != EOF) // This will consume all the previous characters left in the buffer
        ;