Can I use getchar() to clear the buffer between scanf and fgets?

Viewed 419

I have this function and it works well, but I was wondering if the usage of getchar is correct. Could I do something else instead? Thanks, guys.

void addRecord (struct record ** start, int account, char name[], char address[ ]);
{

    printf("Enter your account number:\n");
    scanf("%d", &account);

    getchar();
    printf("Enter your name:\n");
    fgets(name, sizeof name, stdin);
    
    printf("Enter your residential address:\n");
    getaddress(address, sizeof address);
     
}
2 Answers

getchar() will only fetch a single character from stdin . To clear stdin buffer, you have use getchar() until you get EOF (end of file) or a new line. So, instead of calling getchar() once, call it a loop like this:

int c;
do {
    c = getchar();
} while (c != EOF && c != '\n');

Note that the value of EOF is -1, so you must use int to handle it, as char is limited to 0 to 255 range.

Thanks to David Ranieri, the value of EOF can be (and usually) out of the range supported by char , so you should use int (or short ) to handle EOF.

You can put this code inside a function like clear_stdin if you need to reuse this code several times.

Assuming names cannot be empty and are not allowed to start with spaces (or tabs), you can read the name with another scanf while skipping over all intervening whitespace.

    printf("Enter your account number:\n");
    int account;
    if(scanf("%d", &account) != 1) { /* error getting account */ }

    printf("Enter your name:\n");
    char name[80];
    if(scanf(" %79[^\n]", name) != 1) { /* error getting name */ }

The breakdown of the " %79[^\n]" format specifier being used is:

  • the leading space skips over one or more whitespace characters (spaces, tabs, newlines), which consumes the newline left behind by the first scanf, any empty lines, and any leading spaces on the next line;

  • 79 is a width specifier which limits scanf to reading at most 79 characters, leaving room for the terminating \0 nul character in the 80-character destination buffer;

  • [^\n] directs scanf to read a string up to (and not including) the \n newline character, which saves the name that the user entered into the name argument.

Related