これは、これまでの循環配列の私の実装です。5 番目のコマンドの代わりに 6 番目のコマンドを入力し、1 番目のコマンドを破棄することにより、最後に入力された 5 つのコマンドを保存することになっています。これまでのところ、5 つのコマンドを保存して出力することができました。6番目のコマンドで、それが の 2 番目の位置k=1
( もう一度正しい軌道に乗せていただければ幸いです。これがコードの一部です。historyArray
k
0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv[])
{
int i=0;
int j=0;
int k=0;
int tempIndex = 0;
int elementCounter = 0;
char inputString[100];
char *result=NULL;
char delims[] = " ";
char historyArray[5][20] = {0};
char tokenArray[20][20] ;
char hCommand[1][20];
do
{
j = 0;
printf("hshell>");
gets(inputString);
//skip writing "history" in historyArray
if (strcmp(inputString,"history")!= 0)
{
strcpy (historyArray[k], inputString);
}
k = (k+1) % 5;
if (elementCounter <= 5)
elementCounter++;
// Break the string into parts
result = strtok(inputString, delims);
while (result!=NULL)
{
strcpy(tokenArray[j], result);
j++;
result= strtok(NULL, delims);
}
if (strcmp(tokenArray[0], "exit") == 0)
return 0;
if (strcmp(tokenArray[0], "history") == 0)
{
if (j>1)
{
tempIndex = atoi(tokenArray[j]);
puts(tempIndex);
}
else
{
for (i=0; i<elementCounter-1;i++)
printf("%i. %s\n", i+1, historyArray[i]);
}
}
else
{
printf("Command not found\n");
}
} while (1);
}
提案後 (まだ不完全):
j = 0;
//elementCounter = 0;
printf("327>");
gets(inputString);
strcpy (historyArray[k], inputString);
k = (k+1) % 5;
if (elementCounter <= 5)
{
elementCounter++;
}