Gibas Gibas - 1 year ago 133
C Question

scanf 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 Source

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


 #include <stdlib.h>
 printf("Welcome to the Worker Register\n\nWorker Data\n\nName: ");
 fgets(n, 256, stdin);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download