char id;
int num, r;
if (argc != 2) {
printf("error\n");
exit(1);
}
FILE *file = fopen(argv[1], "r");
if (file == NULL) {
printf("error\n");
exit(1);
}
while ((r = fscanf(file, "%c\t%d", &id, &num)) != EOF) {
if(r == 2) {
printf("id: %c, value: %d\n", id, num);
}
else if (r!=2) {
printf("bad input\n");
}
}
The file I'm trying to read looks like:
i 10
i 12
d 10
d 12
(The character/integer are tab separated). My output is:
id: i, value: 10
bad input
id: i, value: 12
bad input
id: d, value: 10
bad input
id: d, value: 12
bad input
WHAT am I doing wrong? "Bad input" should ONLY be printed if the file is incorrectly formatted. The file above demonstrates a properly formatted file. I don't understand how r == 2
and r != 2
at the same time (both conditions are somehow met).
Use
while((r = fscanf(file, " %c\t%d", &id, &num)) != EOF) //Whitespace before %c
Might solve your problem. Because when you use
fscanf(file, "%c\t%d", &id, &num)
Then it leaves a newline character which is consumed in the next iteration.
As your next iteration your id
get \n
and num
gets the character.
But when you put extra white space before %c
which tells fscanf()
to ignore whitespaces(including Tab, space or newline).
Thus your fscanf()
gets two parameter(character and number).
Please change
while ((r = fscanf(file, "%c\t%d", &id, &num)) != EOF) {
to
while ((r = fscanf(file, "%c\t%d\n", &id, &num)) != EOF) {
Adding \n at the end in fscanf.
In your file, lines are terminated with \n. In next read it does not go well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With