无法比拟的令牌 [英] Can't compare tokens

查看:135
本文介绍了无法比拟的令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用C.做了一个code文件来标记数据我想打印一些数据,如果当前标记是等于 SIOL 。我的问题是 STRCMP 将不起作用。你能找出任何错误?这里是code。感谢您的帮助。

  INT的main()
{
    FILE * FP;    焦线[1024];
    字符* VAL1;    FP = FOPEN(sample1.txt,R);
    而(与fgets(线,的sizeof(线),FP)!= NULL)
    {
        VAL1 = strtok的(行,);
        如果(STRCMP(VAL1SIOL)== 0)
        {
            的printf(Sucess!);
            返回0;
        }
        其他
        {
            而(VAL1)
            {
                的printf(%S \\ n,VAL1);
                VAL1 =的strtok(NULL,);
            }
        }
    }
}

sample1.txt是这样的:

  HAHA
SIOL
你好,世界!
SIOL
123 4 345 65 756 867 789797
你好,世界


解决方案

在您的实现的问题是,它没有把 \\ n 正常。

与fgets 遭遇的'\\ n'字符,它返回它作为字符串的一部分。因此,无论是SIOL从文件中的字符串返回到你的程序的SIOL \\ N当你记号化的,因为它们都是在字符串的末尾。 STRCMP 不考虑SIOLSIOL \\ N彼此相等,因此,它返回一个非零值

要解决这个问题,添加的'\\ n'来你的程序接受分隔符的列表:

  VAL1 = strtok的(行,\\ n); //改变的strtok的第二个呼叫,以及

这将确保 strtok的消除的'\\ n'在标记的结尾,并传递干净的令牌还给你。

I made a code to tokenize the data in file using C. I want to print some data if the current token is equal to SIOL. My problem is strcmp won't work. Can you spot any errors? Here is the code. Thank you for your help

int main()
{
    FILE* fp;

    char  line[1024];
    char *val1;

    fp = fopen("sample1.txt" , "r");
    while (fgets(line, sizeof(line), fp) != NULL)
    {
        val1 = strtok(line, " ");
        if (strcmp(val1,"SIOL")==0)
        {
            printf("Sucess!");
            return 0;
        }
        else
        {
            while(val1)
            {
                printf("%s\n", val1);
                val1=strtok(NULL, " ");
            }
        }
    }
}

sample1.txt like this:

HAHA
SIOL
Hello World!
SIOL
123 4 345 65 756 867 789797
Hello World

解决方案

The problem in your implementation is that it does not treat \n properly.

When fgets encounters '\n' character, it returns it as part of the string. Therefore, both "SIOL" strings from your file are returned to your program as "SIOL\n" when you tokenize, because they both are at the end of the string. strcmp does not consider "SIOL" and "SIOL\n" equal to each other, so it returns a non-zero value.

To fix this, add '\n' to the list of delimiters accepted by your program:

val1 = strtok(line, " \n"); // change the second call of strtok as well

This will make sure that strtok eliminates '\n' at the end of the token, and passes a clean token back to you.

这篇关于无法比拟的令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆