簡體   English   中英

使用 strtok 之后,然后使用 strcmp 比較字符串總是錯誤的

[英]After using strtok then using strcmp to compare string is always false

我是 c 的新手,從標准輸入讀取時,如果有空格,我需要分隔單詞。 當我輸入 exit 我想打印 hi 但是當我使用 strcmp 它總是返回 false 並且不打印 hi

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

#define BUFFSIZE 1024
int main()
{
    int n;
    char buffer [BUFFSIZE];
    int pos =0;
    char * parse ;
    char * buf [BUFFSIZE];
    read (STDIN_FILENO, buffer, BUFFSIZE);
    

    parse = strtok(buffer, " ");
    while (parse != NULL) {
        buf[pos] = parse;
        pos++;
    //printf( "%s\n", parse );
        parse = strtok(NULL, " ");
    }
    for (int i=0; i<pos; i++) {
        if (strcmp(buf[i], "exit") ==0) {
            printf("hi");
        }
        printf("%s\n",buf[i]);
    }
    

} // main

您需要進行一些更改,主要在評論中突出顯示。

  1. 在將字符串傳遞給strtok()之前,您需要確保該字符串以空值結尾。
  2. 您需要確保至少在空白和換行符上進行拆分,並且可能還包括制表符和回車符。

您還應該檢查read()是否正常工作並返回數據。

這些變化導致了這樣的事情:

#include <stdio.h>
#include <string.h>
#include <unistd.h>

#define BUFFSIZE 1024
#define DELIMITERS " \n\t\r"

int main(void)
{
    char buffer[BUFFSIZE + 1];  /* Allow for a null terminator */
    int pos = 0;
    char *parse;
    char *buf[BUFFSIZE];
    int nbytes = read(STDIN_FILENO, buffer, BUFFSIZE);
    if (nbytes <= 0)
    {
        fprintf(stderr, "Failed to read anything from standard input\n");
        return 1;
    }
    buffer[nbytes] = '\0';

    parse = strtok(buffer, DELIMITERS);
    while (parse != NULL)
    {
        printf("parse [%s]\n", parse);
        buf[pos] = parse;
        pos++;
        parse = strtok(NULL, DELIMITERS);
    }
    printf("pos = %d\n", pos);
    for (int i = 0; i < pos; i++)
    {
        if (strcmp(buf[i], "exit") == 0)
        {
            printf("found '%s' at index %d\n", buf[i], i);
        }
        printf("%s\n", buf[i]);
    }

    return 0;
}

這包括一些診斷打印。 請注意,消息hi非常不具信息性,尤其是當消息沒有以換行符結尾時。 至少用換行符結束消息。

隨着顯示的更廣泛的分隔符,output 看起來像:

parse [exit]
pos = 1
found 'exit' at index 0
exit
``

With just blank as a delimiter, the output looked like:

```none
parse [exit
]
pos = 1
exit

注意exit后的額外空行。

in due course, the keyword exit will be recognized. ,output為:

parse [in]
parse [due]
parse [course,]
parse [the]
parse [keyword]
parse [exit]
parse [will]
parse [be]
parse [recognized.]
pos = 9
in
due
course,
the
keyword
found 'exit' at index 5
exit
will
be
recognized.

你決定這是否令人滿意。 我認為當檢測到匹配時循環可能應該結束。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM