Search code examples
cscanfinput-buffer

scanf() and clear input buffer in one function in C?


I have the following idea:

I have a function to clear the input buffer:

void clear_inputBuffer()
{
    char c;
    while ( (c = getchar()) != '\n' && c != EOF);
}

Instead of writing for every input

scanf("%d", &selection);
clear_inputBuffer();

I want one function which contains both. Something like this:

int terminalInput(const char *format, ...) {
    int count = 0;
    va_list args;
    // Pass variable parameters
    va_start(args, format);
    count = scanf(format, args);
    va_end(args);

    clear_inputBuffer();
    return count;
}

The function returns 1 but "test" returns also 1 no matter what the correct input is.

int main(int argc, const char * argv[]) {
    int test;
    printf("number:");
    terminalInput("%d", &test);
    printf("Input: %d\n", test);

    return 0;
}

The terminal output:

$ ./a.out
number:345
Input: 1

Solution

  • You can't use scanf with a va_list. You need to use vscanf instead.

    Also, I feel compelled to mention that in general you should almost always avoid using scanf/vscanf entirely; it's notoriously hard to use correctly. Instead, you should read a line of input with fgets (or getline if available) and then use sscanf on the line.