C - Is there a way to differentiate a unity, dozen

2019-08-17 14:32发布

My program need to read i file that indicate if it have to enqueue a number, dequeue a number or finish the program.

I have a .txt file that looks like this:

E    10
E    2
E    300
D
D
D
E    40
E    50
T

So, E say "hey, you have enqueue something" (in first line is 10), D say "hey, dequeue the guy at the head of the queue", and T say "hey, dequeue everyone, free the memory, that's all"

I try using getc but it get every single character, the output is:

E

1
0

And with fgets i have the line, that's not what i want.

What i want is a way to the program understand the difference between 10(decimal), 2(unity), 300(hundreds). How can i get the E than jump the white space, then get 10 (and not 1 then 0)? Is there a function to do this?

Obs: The file with inputs can't be changed, it has to be this way.

标签: c file
1条回答
小情绪 Triste *
2楼-- · 2019-08-17 15:29

You can do something like this:

char c;
while (fscanf(fp, " %c", &c) == 1) {
    switch (c) {
        case 'E': {
            int n;
            if (fscanf(fp, "%d", &n) != 1) {
                input error; handle it
            }
            enqueue(n);
            break;
        }
        case 'D':
            dequeue();
            break;
        case 'T':
            destroy_queue();
            break;
        default:
            unknown command; handle error
    }
}
if (ferror(fp)) {
    input failed; handle error
}

Note that technically this will parse a superset of the file format you described. In particular, it doesn't care about line boundaries or formatting:

E1D

  D    E

2  E  3E
    4   D
     D

is perfectly acceptable and treated the same as

E   1
D
D
E   2
E   3
E   4
D
D

fscanf is used for all input. " %c" skips over any whitespace which may be present and then reads a single character. In particular, after the first line there will always be whitespace which we have to skip over: The \n at the end of the preceding line.

"%d" implicitly skips over any whitespace and reads an integer (in decimal format).

查看更多
登录 后发表回答