Search code examples
cscanfconversion-specifier

C: Scanf string with field skipper "%*" applied on conversion specifier in while loop


I have defined a structure

typedef struct EMP {
    char name[100];
    int id;
    float salary;
} EMP;

and I use it in a while-loop for input

EMP emprecs[3];
int i;

i = 0;
while (i < 3) {
    printf("\nEnter Name: ");
    scanf("%*[\n\t ]%[^\n]s", emprecs[i].name);
    printf("\Enter Id: ");
    scanf("%d", &emprecs[i].id);
    printf("\nEnter Salary: ");
    scanf("%f", &emprecs[i].salary);
    i++;
}

but the loop only takes the first name and skips all other input after that (it finishes, but with empty input). This example is from a C textbook, so where is the problem?

It works somewhat better without the "%*[\n\t ]" field skip, but the textbook tells you to use it.


Solution

  • Try this

    scanf(" %*[\n\t ]%[^\n]s", emprecs[i].name);
          ^^^
         White space
    

    instead of

    scanf("%*[\n\t ]%[^\n]s", emprecs[i].name);
    

    Also,

    scanf(" %d", &emprecs[i].id);
    
    scanf(" %f", &emprecs[i].salary);