简体   繁体   English

C 编程 - 未检测到空格字符

[英]C Programming - Space Character Not Detected

Mainly a Java/Python coder here.这里主要是 Java/Python 编码器。 I am coding a tokenizer for an assignment.我正在为一项任务编写分词器。 (I explicitly cannot use strtok() .) The code below is meant to separate the file text into lexemes (aka words and notable characters). (我明确地不能使用strtok() 。)下面的代码旨在将文件文本分成词素(又名单词和显着字符)。

char inText[256];
fgets(inText, 256, inf);

char lexemes[256][256];
int x = 0;

char string[256] = "\0";
for(int i=0; inText[i] != '\0'; i++)
{
    char delims[] = " (){}";
    char token = inText[i];

    if(strstr(delims, &inText[i]) != NULL)
    {
        if(inText[i] == ' ') // <-- Problem Code
        {
            if(strlen(string) > 0)
            {
                strcpy(lexemes[x], string);
                x++;
                strcpy(string, "\0");
                (*numLex)++;
            }
        }
        else if(inText[i] == '(')
        {
            if(strlen(string) > 0)
            {
                strcpy(lexemes[x], string);
                x++;
                strcpy(string, "\0");
                (*numLex)++;
            }
            strcpy(lexemes[x], &token);
            x++;
            (*numLex)++;
        }
        else
        {
            strcpy(lexemes[x], &token);
            x++;
            (*numLex)++;
        }
    }
    else
    {
        strcat(string, (char[2]){token});
    }
}

For some odd reason, my code cannot recognize the space character as ' ' , as 32 , or by using isspace() .出于某种奇怪的原因,我的代码无法将空格字符识别为' '32或使用isspace() There are no error messages, and I have confirmed that the code is reaching the space in the text.没有错误消息,我已经确认代码到达了文本中的空格。

This is driving me insane.这让我发疯。 Does anyone have any idea what is happening here?有谁知道这里发生了什么?

You are using the function strstr incorrectly.您错误地使用了 function strstr

if(strstr(delims, &inText[i]) != NULL)

the function searches exactly the string pointed to by the pointer expression &inText[i] in the string " (){}" . function 在字符串" (){}"中精确搜索指针表达式&inText[i]指向的字符串。

Instead you need to use another function that is strcspn .相反,您需要使用另一个 function ,即strcspn

Something like就像是

i = strcspn( &inText[i], delims );

or you can introduce another variable like for example或者你可以引入另一个变量,例如

size_t n = strcspn( &inText[i], delims );

depending on the logic of the processing you are going to follow.取决于您要遵循的处理逻辑。

Or more probably you need to use the function strchr like或者更可能您需要使用 function strchr类的

if(strchr( delims, inText[i]) != NULL)

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

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