2017-05-25 75 views
-2

我想達到的目標:我要拆分輸入,並把它分成不同的陣列。
例子:錯誤:賦值表達式與數組類型

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,然後將其放入數組中,但效率不高。

P.S:我知道我會得到一個評論說,不使用gets(),使用fgets()防止溢出。我建議你不要發表評論。由於我的老師,我必須使用,但稍後會因我的使用而改變。

+0

使用'strcpy'(或如)代替'='。 – BLUEPIXY

+0

但我希望分割輸入並將其放入不同的數組中。 @BLUEPIXY –

+1

這裏有一個uininitalized變量。也許,請閱讀關於'strtok'的手冊頁並查看它返回的內容?至於'fgets'和'gets',在那裏使用這個評論,矛盾的是,你認爲考慮到你在代碼中存在錯誤嗎? – t0mm13b

回答

0

在我的代碼的問題並沒有初始化istrtok。我認爲當聲明一個var時,它的值爲0.這是一個錯誤,並且使用strtok這樣做是不對的,因爲你不能將一個數組分配給一個數組。您應該使用strcpy來代替,並且您將獲得相同的結果。

+0

你明白了。 'strtok()'返回一個指向char的指針,它不能被分配給char數組。 – SiggiSv