pseudoabdul
pseudoabdul

Reputation: 636

fscanf reading newline character

I have been slowly tracking down my error for my program. I have narrowed it down to this. I have a user input

fscanf(stdin, "%c %c %d", &car, &dir, &amount);

the first time I access it it works fine, correctly reading in the values. The second time in the loop it reads a \n into car instead of the char I give it. it then reads what should have been in car into dir. amount reads correctly. As car is passed to other functions for counting I eventually end up with a segfault.

Is it reading in the \n from the previous line or something?

Upvotes: 0

Views: 2042

Answers (1)

pmg
pmg

Reputation: 108938

The "%c" conversion specifier does not do the usual whitespace trimming.
Try adding a space before the first conversion specifier

if (fscanf(stdin, " %c %c %d", &var, &dir, &amount) != 3) { /* error */ }

Or, maybe better, read a full line and parse it within your program

char buf[1000];
fgets(buf, sizeof buf, stdin);
parse(buf);

Upvotes: 1

Related Questions