【问题标题】:C prints first character of the array only, does not print the rest?C 只打印数组的第一个字符,不打印其余字符?
【发布时间】:2014-09-07 05:30:02
【问题描述】:

基本上我必须标记一个 4 列的行并将这些标记放入一个数组中,所以我在下面创建了这个函数。

char** tokeniser(char* lineToToken)
{
    int i = 0;
    char** tokenList = malloc(4*sizeof(char*));
    char* token;
    while ((token = strtok(lineToToken, " ")) != NULL && i<4)
    {
        tokenList[i] = malloc(strlen(token) + 1);
        strcpy(tokenList[i], token);
        ++i;
    }
    return tokenList;
}

主要是我有一个简单的东西来测试它,并且只将第一个元素打印 4 次..

for(int i = 0; i<3; i++)
{
    printf("%s", tokenList[i]);
}

我输入的文本文件是 “asda asdasd 23 asd”,但我只得到 asda 4 次:S

【问题讨论】:

  • strtok() 不是这样工作的。

标签: c arrays string pointers memory


【解决方案1】:

问题在于您对strtok() 的使用。 cplusplus.com 的文档说得最好:

在第一次调用时,该函数需要一个 C 字符串作为 str 的参数,其第一个字符用作扫描标记的起始位置。在随后的调用中,该函数需要一个空指针,并使用最后一个标记结束后的位置作为新的扫描起始位置

总而言之,您是在一遍又一遍地传递要标记化的字符串,而不是仅在第一次传递它(以及NULL 随后的时间)

因此,以下程序可能会为您提供所需的示例:

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

char** tokeniser(char* lineToToken)
{
    int i = 0;
    char** tokenList = (char**) malloc(4 * sizeof(char*));
    char* token = strtok(lineToToken, " ");
    while(token != NULL && i < 4)
    {
        tokenList[i] = (char*) malloc(strlen(token) + 1);
        strcpy(tokenList[i], token);
        token = strtok(NULL, " ");
        ++i;
    }
    return tokenList;
}

int main(int argc, char const* argv[])
{
    char str[] = "asda asdasd 23 asd";
    char** tokenList = tokeniser(str);

    for(int i = 0; i < 4; ++i)
    {
        printf("%s\n", tokenList[i]);
    }
    return 0;
}

在我的机器上打印:

asda
asdasd
23
asd

【讨论】:

  • 如果i &lt; 4tokenList 未完全初始化。也许添加while (i&lt;4) tokenList[i++] = NULL;
  • @chux 好点,虽然这不是我个人写东西的方式!一想到要在里面硬编码4,我就不寒而栗。
  • 是的,最好传入char** tokeniser(char* lineToToken, size_t sz)
【解决方案2】:

在上述函数中,每次 Strtok 函数都传递相同字符串的起始地址。

strtok 函数的调用方式一般如下。

#include<stdio.h>
#include<string.h>
void main() {
    char Src[25]="Hare Krishna Hare Rama";
    char C[2]=" ";
    char *del=C;
    char *temp[5];
    int  i=0;
    temp[i] = strtok(Src,del);
    while(temp[i] !=NULL) {

        printf("The str is <%s\n>",temp[i]);
        temp[++i] = strtok(NULL,del);

    }

}

当您第一次调用时,您必须传递字符串的起始地址和分隔符。 然后strtok返回指向分隔符的起始指针。所以下次调用时不需要传递字符串的起始地址,strtok会记住指向分隔符下一个字符的地址。所以后续调用应该用空指针。

【讨论】:

    猜你喜欢
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多