0

I am facing issue with fgets when user tries to enter data for second time (skips first input).. working fine first time.. as shown in image below: enter image description here

I am using following code:

printf("Please Enter Following Information: \n\n\n");
        printf("County (For Example - Hamilton,Ohio): \n");
        fgets(strCounty, 49, stdin);
         /* we should trim newline if there is one */
        if (strCounty[strlen(strCounty) - 1] == '\n') {
            strCounty[strlen(strCounty) - 1] = '\0';
        }
        printf("Race of head of Household (For Example - Asian): \n");
        fgets(strRace, 49, stdin);
        /* again: we should trim newline if there is one */
        if (strRace[strlen(strRace) - 1] == '\n') {
            strRace[strlen(strRace) - 1] = '\0';
        }
        printf("Number in Household: \n"); 
        scanf("%d",&intHouseholds);
        printf("The household yearly income: \n");
        scanf("%d",&dblIncome);

I have seen a lot of related questions but haven't found the correct answer - please help.

melpomene
  • 84,125
  • 8
  • 85
  • 148
Coder
  • 3
  • 2
  • Your example is missing vital information... i.e., where and how is `strCounty` defined? – Myst Apr 16 '17 at 16:27
  • 2
    Try adding `fprintf(stderr, "%d\n", (int)strlen(strCounty));` before you trim the newline. My guess is that the last call to `scanf` left the `\n` in the input buffer, so the first `fgets` picks it up when your loop runs again. –  Apr 16 '17 at 16:30
  • @Myst here is how it is defined : – Coder Apr 16 '17 at 16:36
  • `char strCounty[50]="";` `char strRace[50]="";` `int intHouseholds = 0;` `double dblIncome = 0;` – Coder Apr 16 '17 at 16:38
  • 1
    Per your image, this is in a loop, and the newline remaining after the income input is the consumed limiter of the *next* iteration's ensuing `fgets`. And I'm surprised *none* of the questions you looked at were helpful, as this has been asked *hundreds* of times: [`fgets` doesn't work after `scanf`](https://stackoverflow.com/questions/5918079/fgets-doesnt-work-after-scanf), for example. – WhozCraig Apr 16 '17 at 16:43
  • @WhozCraig Thank you for pointing me in the right direction :) also I apologize for asking a question that has already been answered.. – Coder Apr 16 '17 at 17:16

0 Answers0