1

My program compiles ok but it when it calls the getinput() function it never prompts for input.

Edited to show more code, I added fflush but it still skips it for some reason.

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


main(){

    char mystring[] = "It's equal to it. ";
    int k = 32;
    int e;
    printf("Enter a number: ");
    scanf("%d",&e);
    if(e == k){
        printf("\n\n%s\n",mystring);

    } else if(e < k){
        printf("\n\n%d\n",e);

    } else {


        getinput();
    }

    exit(0);

}

int getinput(){

    char gettext[64];

    printf("Enter text here: ");
    fflush(stdout);
    fgets(gettext, 64, stdin);
    printf("\n\nYou entered: %s\n\n",gettext);
    return 0;


}
melpomene
  • 84,125
  • 8
  • 85
  • 148
Skilo Skilo
  • 526
  • 4
  • 11
  • 23
  • Your title says it skips `fgets`, but your question is more about `printf`. – Barmar Nov 22 '13 at 17:27
  • @WillBD Looks like that question is a different problem, because of mixing `scanf` and `fgets`. – Barmar Nov 22 '13 at 17:35
  • Ah, a good point, I didn't see your comment (and therefore re-read the question) until after I put mine up, good catch. – WillBD Nov 22 '13 at 17:37
  • @WillBD It turns out you were presciently correct. He's added more code to the question. – Barmar Nov 22 '13 at 17:48
  • @Barmar yea but scanf is not used inside the getinput function so i don't see why that would matter. – Skilo Skilo Nov 22 '13 at 17:52
  • It's used BEFORE the `getinput()` function. What matters is the state of the `stdin` stream when `getinput()` is called. – Barmar Nov 22 '13 at 17:52

2 Answers2

4

after this line scanf("%d",&e) add a getchar() like this :

scanf("%d",&e);
getchar();

when you press Enter the newline character stays in the buffer so when fgets is called the newline is passed to it and it actes as if you pressed Enter

Farouq Jouti
  • 1,657
  • 9
  • 15
  • You've got the right idea about what's going on here. However, `getchar()` isn't a robust fix. I think there's a way to put some extra stuff in the `scanf()` format to make it "eat" the rest of the line, but I'm still working out the best way to do that. I'll post when I have more details... – Dave Lillethun Nov 23 '13 at 00:21
  • Okay, here's what seems to work: `scanf("%d%*[^\n]", &e); assert('\n' == getchar());` The assert is optional of course (but the getchar() is not). I just wanted to be sure I was eating the newline, and not some other character by accident. The `%*[^\n]` that I added basically says "match everything that is not a newline" (`[^\n]` pattern) "but do not assign it to any variable" (that's what the `*` does). – Dave Lillethun Nov 23 '13 at 00:34
1

Try calling fflush(stdout); after your first printf.

printf will flush it for you, but only when it has a newline at the end (e.g. printf("hi\n");)

noelicus
  • 14,468
  • 3
  • 92
  • 111