简体   繁体   English

C语言中的令牌读取困难

[英]Trouble reading in Tokens in C

I can't seem to figure out, how to correctly read in a .txt file that has the following appereance: (example) 我似乎无法弄清楚如何正确读取具有以下外观的.txt文件:(示例)

+ 1
+ 2
- 2
+ 5
p -1
? 5

and so on... what I need now is to store the operator / token which can be '+' '-' 'p' or something like that, and the int that follows in two different variables because I need to check them later on. 依此类推...我现在需要存储的运算符/令牌可以是'+''-''p'或类似的东西,以及后面跟着两个不同变量的int,因为我以后需要检查它们上。

char oprtr[1];
int value;
FILE *fp = fopen(args[1], "r");

while(!feof(fp) && !ferror(fp)){
    if(fscanf(fp, "%s %d\n", oprtr, &value) < 1){
        printf("fscanf error\n");
    }
    if(strcmp(oprtr, "+") == 0){
        function1(bst, value);

    } else if(strcmp(oprtr, "-") == 0){
        function2(bst, value);

    } else if((strcmp(oprtr, "p") == 0) && value == -1){
        function3(root);
    //some other functions and so on...
    }

printing out oprtr and value in the loop shows that they are not being red in correctly, but it does compile. 打印出oprtr和循环中的值表明它们并没有被正确地红色填充,但是可以编译。 Does someone have a solution? 有人有解决方案吗?

You have single characters, you can use == to compare them instead of strcmp . 您只有一个字符,可以使用==而不是strcmp进行比较。 Just read the input in pairs and use a switch for example. 只需成对读取输入并使用一个switch

char c;
int x;

while(fscanf(fp, "%c %d", &c, &x) == 2)
{   switch(c)
    {   case '+': /* ... */
    }
}

Your string oprtr is too small to hold anything but an empty string (remember that C strings need a terminating 0 character!). 您的字符串oprtr太小,无法容纳空字符串(请记住C字符串需要以0结尾的字符!)。 So: 所以:

char oprtr[1];

needs to be at least: 至少需要:

char oprtr[2];         // string of maximum size 1

or more defensively: 或更防御地:

char oprtr[256];       // string of maximum size 255

You can use the fscanf function, you can get the input from the file. 您可以使用fscanf函数,您可以从文件中获取输入。

int fscanf(FILE *stream, const char *format, ...);

fscanf(fp," %c %d",&c,&d);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM