I’m using strcmp to compare character arrays in c++, but I get the following error for every occurrence of strcmp: error: invalid conversion from ‘int’ to ‘const char*’ followed by: error: initializing argument 2 of ‘int strcmp(const char*, const char*)’
I’ve include string, string.h, and stdio.h and here is my code, thanks to all who reply.
Also, is there a better way to check the buffer other than a bunch of if statements?
int main(int argc, char* argv[])
{
unsigned count = 0;
bool terminate = false;
char buffer[128];
do {
// Print prompt and get input
count++;
print_prompt(count);
cin.getline(buffer, 128);
// check if input was greater than 128, then check for built-in commands
// and finally execute command
if (cin.fail()) {
cerr << "Error: Commands must be no more than 128 characters!" << endl;
}
else if ( strcmp(buffer, 'hist') == 0 ) {
print_Hist();
}
else if ( strcmp(buffer, 'curPid') == 0 ) {
// get curPid
}
else if ( strncmp(buffer, 'cd ', 3) == 0 ) {
// change directory
}
else if ( strcmp(buffer, 'quit') == 0 ) {
terminate = true;
}
else {
//run external command
}
} while(!terminate);
return 0;
}
Your comparison string are incorrect. They should be of the form
"hist", not'hist'.In C++,
'hist'is simply a character literal (as stated in section 2.14.3 of the C++0x draft (n2914) standard), my emphasis on the last paragraph:As to there being a better way, it depends on what you mean by better 🙂
One possibility is to set up a functon table which is basically an array of structs, each containing a word and a function pointer.
Then you simply extract the word from your string and do a lookup in that array, calling the function if you find a match. The following C program shows how to use function tables. As to whether that’s a better solution, I’ll leave it up to you (it’s a moderately advanced technique) – you may be better off sticking with what you understand.
When run with:
you get the output: