0

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.

Toby
  • 9,696
  • 16
  • 68
  • 132
Hessu
  • 49
  • 6

1 Answers1

-3

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);
msc
  • 33,420
  • 29
  • 119
  • 214
  • 1
    `%d` and `%f` already skip whitespace. So the space behind it is superfluous. In fact, only `%c`, `%[` and `%n` are the format specifiers to which whitespace matters. And `%*[\n\t ]` is superfluous too after you've added before it. – Spikatrix Apr 14 '17 at 11:24
  • I got it working by using the white space before % in all scanfs AND by removing the %*[\n\t ]. Thank you for the tip! I still don't understand why the field skip is not working the way the textbook said. – Hessu Apr 14 '17 at 11:58