简体   繁体   English

strtok给出了空字符串或我不知道的东西

[英]strtok gives empty string or something I don't know

I have the following source-code: 我有以下源代码:

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

int main(int argc, char *argv[])
{

    char string[100];
    printf("Give me some text. \n");
    fgets(string, 100, stdin);

    char delimiter[]=" ";
    char *erg;

    erg=strtok(string, delimiter);

    while(erg != NULL){
        printf("Wort: %s \n", erg);

        erg=strtok(NULL, delimiter);
    }

    return 0;
}

When I for example put in the text "abc def", the program is working like I want it to work. 例如,当我输入文本“ abc def”时,该程序就可以像我希望的那样工作。 It print out the words "abc" and "def". 它打印出单词“ abc”和“ def”。 But when I put in the text "abc def ", it prints out "abc", "def" and "". 但是当我输入文本“ abc def”时,它会打印出“ abc”,“ def”和“”。 I don't want to print out the last empty "". 我不想打印出最后一个空的“”。 Can someone please tell me how to filter that ? 有人可以告诉我如何过滤吗?

Gruß, Andre 安德烈·格鲁斯(Gruß)

IMO, you need to get rid of the last \\n read by fgets() in fgets(string, 100, stdin); IMO,您需要摆脱fgets(string, 100, stdin); fgets()读取的最后\\n fgets(string, 100, stdin);

You can do this in many ways, like 您可以通过多种方式执行此操作,例如

  1. include the \\n in your delimiter list. 在分隔符列表中包含\\n " \\n" , for example. 例如" \\n"
  2. manually check the length of string, and at the last position, replace the \\n with a \\0 . 手动检查字符串的长度,并在最后位置将\\n替换为\\0

fgets gets a whole string along with the \\n character which you press after entering the string.So use fgets会得到一个完整的字符串以及在输入字符串后按下的\\n字符。

string[strlen(string)-1]='\0';

to replace the \\n in string with a \\0 . \\0替换string\\n

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

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