Gibas Gibas - 1 month ago 20
C Question

Printf is skipped (?)

I tried to do a small Worker Register, but it skips completely the second scanf, which gets address value. I am a beginner, so I do not know what I am doing wrong. Here is the code:

#include <stdio.h>

int main()
{
// var
char n[256], ad[256]; // n - Name, ad - Address
int i, ag; // i - Income, ag - Age
// code
printf("Welcome to the Worker Register\n\nWorker Data\n\nName: ");
scanf("%255[^\n]", n);
printf("Address: ");
scanf("%255[^\n]", ad);
printf("Age: ");
scanf("%d", &ag);
printf("Income: R$");
scanf("%d", &i);
printf("Worker %s\nAddress: %s\nAge: %d\nIncome: R$%d", n, ad, ag, i);
return 0;
}


I really appreciate any help you can provide!

Answer

Nad's hack of adding a getchar() seems to fix it, but I wouldn't use scanf for reading strings if I were you.

It's nicer to use fgets() reading strings instead. scanf on a string is problematic. See: Reading a string with scanf

e.g.

 #include <stdlib.h>
 ...
 printf("Welcome to the Worker Register\n\nWorker Data\n\nName: ");
 fgets(n, 256, stdin);
 ...