Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

c - fill two dimensional array with parts of a string

I want the parts of the string I broke to be entered to a two-dimensional array, for example: String: "one day" Result in array: Col1: one Col2: day

The question is, how do I fill the array with those two variables result2 for column 1 and result for column 2?

This is my code so far(as you can see i have a separate array for history and a separate array for holding the parts of the user input):

#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 
",i+1,historyArray[i]);
                    }
                }  
                else if (strcmp ("exit",inputString) != 0)
                {
                    printf("
Command not found 
");
                }

    }while (strcmp ("exit", inputString) != 0);
    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First, it sounds like you need a single dimensional array for input:

  char tokenArray[100];

Then farther down, the loop would do this:

result = strtok(inputString, delims);

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

Try with that hint and see about the rest.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...