Reputation: 21019
I have a file which will contains basic mathematical operations. An example:
1 + 23 / 42 * 23
I am scanning the file, putting each "element" into a struct and pushing it onto a stack I created. The problem I have is as follows:
char reading;
while(!feof(fp)) {
fscanf(fp, "%c", &reading);
....
This will scan 1
, +
, 2
, 3
instead of 1
, +
, 23
. What are other suggestions to use one fscanf
and have it iterate and read all the inputs as intended to with respect to their type?
Regards,
Upvotes: 1
Views: 142
Reputation: 14792
You should use fscanf()
a bit different, like this:
char buf[16];
int val;
char op;
while (!feof(fp)) {
fscanf("%s ", buf); // Note: Without ' ' the last value would be readed twice
if (buf[0] == '+' || buf[0] == '-' || buf[0] == '/' || buf[0] == '*') {
op = buf[0];
// do something with op
} else {
sscanf(buf, "%d", &val);
// do something with val
}
}
The size of buf
must be something which could store the length of your numbers.
Upvotes: 0
Reputation: 375634
fscanf
is the wrong tool for this job, because it needs a format string that knows in advance what format to expect. Your best bet is to read a character at a time and build up tokens that you can then interpret, especially if you'll have to accept input like 2+2
(no spaces), or (1 + 23) / 42
, with parentheses.
Upvotes: 1