Search code examples
cscanfbuffernewline

Issue with clearing buffer in C


I'm trying to read some strings from keyboard and save them to the arrays. I specified maximum number of characters to be read and clear buffer after middle initials to discard all character and exceed limit. Everything seems fine as soons as I type more than maximum characters. But what if I type less than maximum? I get and additional empty line. It seems like program is waiting for input, and I don't know why. Can somebody shed the light on this shadow of my knowledge?

Here is my code snippet

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>


int main(void)
{
    char name[35];
    char middlename[7];
    char lastname[35];

    printf("Please enter name: ");
    scanf("%34[^\n]%*c", name);

    printf("Please enter middle name: ");
    scanf("%6[^\n]%*c", middlename);
    while (getchar() != '\n');

    printf("Please enter last name: ");
    scanf("%34[^\n]%*c", lastname);
}

This is my output :

Please enter name: Antony
Please enter middle name: Jr.
_ // here it waits for input

Solution

  • In each call of scanf like this

    scanf("%34[^\n]%*c", name);
    

    remove the second conversion specifier

    scanf("%34[^\n]", name);
    

    and instead of it use the loop

    while (getchar() != '\n');
    

    Otherwise for example in this code snippet

    scanf("%6[^\n]%*c", middlename);
    while (getchar() != '\n');
    

    you are trying to read the new line character '\n' two times.

    Another approach is the following

    printf("Please enter name: ");
    scanf("%34[^\n]%*[^\n]", name);
    
    printf("Please enter middle name: ");
    scanf(" %6[^\n]%*[^\n]", middlename);
    
    printf("Please enter last name: ");
    scanf(" %34[^\n]*[^\n]", lastname);
    

    Pay attention to the blank in the second and the third calls of scanf that precedes the first format specifier.