“C

时间:2017-04-07 10:16:18

标签: c string struct strtok

我正在编写一个程序,我必须定义自己的以下函数版本:

int AtoI ( const char * str );
int StrCmp ( const char * str1, const char * str2 );
char * StrCpy ( char * destination, const char * source );
char * StrCat ( char * destination, const char * source );
char * StrChr ( char * str, int character );

在main函数中,我需要声明一个名为wordlist的类型为myWord的大小为20的数组。然后,使用strtok()库函数,从字符串MyString中提取每个单词并将其存储在wordlist中。但是,我一直收到错误消息:

incompatible type for argument 1 of ‘strcpy’

为该行:

strcpy(wordlist[i], token);

如何解决此问题?到目前为止,这就是我所拥有的:

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

struct myWord{
    char word[21];
    int length;
};

int main(void){
    typedef struct myWord myword;
    int i = 0;
    myword wordlist[20];
    char *myString = "the cat in the hat jumped over the lazy fox";

    char *token;
    token = strtok(myString, " ");

    while(myString != NULL){
        strcpy(wordlist[i], token);
        token = strtok(NULL, " ");
        printf("%s\n", wordlist[i]);
        i++;
    }

}

1 个答案:

答案 0 :(得分:0)

更正的代码是

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

typedef struct myWord{
    char word[21];
    int length;
}myword;

int main(void){
    int i = 0;
    myword wordlist[20];
    char myString[] = "the cat in the hat jumped over the lazy fox";

    char *token;
    token = strtok(myString, " ");

    while(token != NULL){
        strcpy(wordlist[i].word, token);
        token = strtok(NULL, " ");
        printf("%s\n", wordlist[i].word);
        i++;
    }    
}
  1. 您的结构的C字符串成员是word,因此您必须将该成员传递给strcpyprintf
  2. 您的循环必须检查token返回的strtok以检查字符串是否已到达
  3. strtok修改你的字符串来完成这项工作,所以字符串必须是可修改的,你不能使用指向字符串文字的指针。
相关问题