我想要实现的目标:我希望将输入拆分并放入不同的数组中。例:

The user enters: 1337 Hello World
//Programs split input and store 1337 in str1 and Hello World in str2


我有一个代码会产生此错误:


  main.c:19:12: error: assignment to expression with array type

str2[i] = strtok(NULL, "\n");
        ^



码:

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

int main(){
    char input[1000], str1[100][1000], str2[100][1000];
    int i;

    for(;; i++){
        printf("Enter a day and remainder: ");
        gets(input);

        if(strcmp(input, "0") == 0)
            break;
        else{
            str1[i] = strtok(input," ");//The cause of the error
            str2[i] = strtok(NULL, "\n");
        }
    }
   return 0;
}


我已经对这个错误进行了研究。从我学到的知识,您不能将数组分配给var,但这不是我要尝试的方法。我正在将数组值分配给数组。我认为问题出在strtok函数中,因为我认为它用作char值。我想做的是将输入拆分并将其放入不同的var中,然后将其放入数组中,但这效率不高。

附注:我知道我会收到一条评论,说不要使用gets(),请使用fgets()防止溢出。我建议您不要发表评论。由于老师的缘故,我必须使用,但稍后会更改。

最佳答案

我的代码中的问题不是初始化istrtok。我假设声明一个var时,它的值为0。这是一个错误,使用strtok这样不正确,因为您不能将数组分配给数组。您应该改用strcpy,您将获得相同的结果。

关于c - 错误:分配给具有数组类型的表达式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44191246/

10-12 00:31
查看更多