2013-02-19 44 views
0

我希望我輸入的字符串部分輸入到二維數組中,例如: 字符串:「一天」 數組中的結果:Col1:一個Col2 :天使用部分字符串填充二維數組

現在的問題是,如何填充第2列的result2列和列2的result這兩個變量的數組?

這是到目前爲止我的代碼(你可以看到我對歷史的獨立陣列和用於保持用戶輸入的部分單獨陣列):

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

int main (int argc, char *argv[]) 
{ 
    int i=0; int j=0; int k=0; 
    char inputString[100]; 
    char *result=NULL; 
    char *result2=NULL; 
    char delims[] = " "; 
    char historyArray[100][100] = {0}; 
    char historyKey[] = "history"; 
    char *tokenArray[100][100] = {0} ; 
    //char exitString[] = "exit"; 

    do 
    { 

      printf("hshell>"); 
      gets(inputString); 
      strcpy (historyArray[k], inputString); 
      k++; 


      // Break the string into parts 
      result = strtok(inputString, delims); 

      while (result!=NULL) 
      { 
        result2 = result; 
        puts(result); 
        result= strtok(NULL, delims); 
        for (int count = 0; count < k; count++) 
        tokenArray[count] = result2; 
        j++; 
      } 



       if (strcmp(inputString,historyKey) == 0) 
       { 
        for (i=0; i<k; i++) 
        { 
         printf("%d. %s \n",i+1,historyArray[i]); 
        } 
       } 
       else if (strcmp ("exit",inputString) != 0) 
       { 
        printf("\nCommand not found \n"); 
       } 

    }while (strcmp ("exit", inputString) != 0); 
    return 0; 
} 
+1

我沒有看到問題?添加了 – 2013-02-19 19:09:45

+0

。對於那個很抱歉。 – serge 2013-02-19 19:11:52

回答

1

首先,這聽起來像你需要爲輸入的一維陣列:

char tokenArray[100]; 

然後越往下,循環這樣做:

result = strtok(inputString, delims); 

j = 0; 
while (result!=NULL) 
{ 
    strcpy(tokenArray[j++], result); 
    puts(result); 
    result= strtok(NULL, delims); 
} 

試試這個提示,看看其餘的。

+0

簡單但比使用兩個變量更高效。有用。謝謝 – serge 2013-02-19 19:25:24

+0

當我調試程序時,當我輸入「history」時,tokenArray在一個地址中的值爲「history」,在下一個地址中的值爲「tory」。我認爲這阻止了我檢查tokenArray [1]是否爲NULL。這是怎麼發生的? – serge 2013-02-19 19:41:34