问题
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 \n",i+1,historyArray[i]);
}
}
else if (strcmp ("exit",inputString) != 0)
{
printf("\nCommand not found \n");
}
}while (strcmp ("exit", inputString) != 0);
return 0;
}
回答1:
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.
来源:https://stackoverflow.com/questions/14965436/fill-two-dimensional-array-with-parts-of-a-string