So I was asked to write a little program in class. I'm learning to code in C and I have problems with this function and the usage of fscanf function, when trying to store a value in different variables depending on its type.
What it is supposed to do is written in comments by my teachers, the rest is my code (I'm not supposed to use any other libraries apart from the included ones):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* A) Tries to read a double from the file and asign its value to the double pointed by num. If it was possible returns 1.
B) In other case, tries to read a string up to 31 chars and stores its value on the string
pointed by op, if it was possible returns 2.
C) In any other case it returns 0 (end of file, etc)*/
int num_or_op(FILE* f, double *num, char *op) {
int aux;
int read = 0;
read = fscanf(f, "%lf", num);
if (read==-1) /*eof*/
return 0;
if (read==0){
aux = fscanf(f, "%31s", op);
if (aux>0){
read=2;
}
}
return read;
}
The problem I'm finding is, following this steps, the program is skipping some characters. I call this function in a while block to store all the data.
If I introduce a file with, for example, 1 2 + 3, it reads 1 and 2, then it's unable to store +
correctly but instead of doing it in the next fscanf, it just scans the number 3 and adds it to the string pointed by op.
I thought when fscanf
returned 0, the next call to fscanf
read the same character that couldn't be read before if the format is correct this time, but apparently it doesn't work that way or I'm probably doing something wrong. I was able to come up with different alternatives, but is there any way to do this in the order that is specified, A,B,C and reading directly from the file with fscanf (not using fgets to get a line for example)? I was asked to do it with this specific function.
In case it matters I'm compiling with gcc -ansi -pedantic -Wall -Wextra -Werror -o program program.c
Thanks.
The right answer was given by @user3386109 in a comment so I add the explanation here to close the question.
After a conversion error with this function, the standard only requires one character of push back, and I am using an implementation that meets the minimum required push back. A good example is the input -.a
. The parser needs to read three characters to determine that the input isn't a valid double
. If it only pushes back one character the -
and .
are lost. In my case +
and space are read, and only the space is pushed back. My program is running C version C89/C90.