Hi,
This is the working program in C .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
// test command prompt
#include<cstdio>
#include<cstring>
int main() {
char input[256];
char *pch[10]; // array of character pointers
bool done = false;
printf("||.:: Command Prompt ::.||\n");
while (!done) {
printf("O-Shell -> ");
gets(input);
int i = 0;
if ((pch[i] = strtok(input, " ")) == NULL) {
printf("You need to enter a command.\n");
continue;
}
i++;
while(pch[i] = strtok(NULL, " ")) //assign strtok(NULL," ") to pch[i] and then checks it for NULL (its a shorthand notation)
i++;
if (pch[1] && strcmp(pch[0], "exit") == 0) {
if (strcmp(pch[1], "true") == 0) {
printf("Exiting...\n");
done = true;
} else if (strcmp(pch[1], "false") == 0) {
printf("Exiting... just kidding!\n");
done = false;
}
} else {
printf("Invalid command.\n");
}
}
return 0;
}
|
Let us look at the changes I've made.
1. In your code , at line 23 and 23 you did :
1 2
|
if (strcmp(pch, "exit") == 0) {
if (strcmp(pch, "true") == 0) {
|
pch is a pointer to a single string. Its too much obvious that if pch is equal to "exit" then how can it be equal to "true" also !!!!
2. You basically need an array of character pointers where each array element will hold each word of the command. This is what I've done above.
3. In my code , if you write line 23 as
if (strcmp(pch[0],"exit") == 0
) instead of what i've written then the program will crash if you give the command as : exit
because then there will be no pch[1] and hence doing strcmp on it will produce a segmentation fault.
This is the program output (Hope this is what up want to achieve )
||.:: Command Prompt ::.||
O-Shell ->
You need to enter a command.
O-Shell ->
You need to enter a command.
O-Shell ->
You need to enter a command.
O-Shell -> exit false
Exiting... just kidding!
O-Shell -> exit
Invalid command.
O-Shell -> exit true
Exiting... |