0

I know there are a lot of questions about this, but i need a solution to flush the STDIN input buffer without pressing any key or 'enter'.

I'm using fgets(char, size, char) (on a loop) to get an input stream from the keyboard and I want to press just 1 'enter' and go to the next input WITHOUT allocating the stdin buffer (if the buffer is bigger than the one specified on fgets, the first char array will be good but the next fgets on the loop will write the rest of the buffer on the next char array)

Most of the solutions on SO are like this:

/** deletes the buffer on stdin */
void flushStdin(){
    int c;
    while ((c = getchar()) != '\n' && c != EOF);
}

But this needs to press 'enter'. My whole code looks like this:

void readString(char *arrayString){

    fgets(arrayString, BUF_SIZE * sizeof(arrayString), stdin); //1st Enter here
    flushStdin(); //2nd Enter here

    //Deletes the newline '\n' at the end
    size_t len = strlen(arrayString);
    if (len > 0 && arrayString[len-1] == '\n')
        arrayString[--len] = '\0';

    return;
}

Thank you!

Hans Araya
  • 345
  • 2
  • 15
  • 1
    At least for me it's very unclear what you mean. Why do you need to flush something? What do you mean by "allocating the stdin buffer"? Also why are you multiplying BUF_SIZE with the size of a pointer? – Sami Kuhmonen Aug 21 '16 at 08:26
  • You shouldn't call `fflushStdin` unless `fgets` filled the whole buffer, and there isn't a `'\n'` at the end of the buffer. Also, like SamiKuhmonen said, you should not multiply `BUF_SIZE` by any other number. – user3386109 Aug 21 '16 at 08:37
  • Input? Expected output? Actual output? BUFSIZE? – Support Ukraine Aug 21 '16 at 08:49

0 Answers0