I’m trying to learn C++, and I learn by doing…
What this code’s end-result is going to be is that it outputs the char* argv[2] to a function which only takes strings as input, and it will output a changed string.
How can I convert char* argv[2] into a string?
Everything I’ve tried ends up crashing my command prompt, for some reason.
int main(int argc, char* argv[])
{
std::string com2 = argv[2];
char* com1[4];
com1[1] = "-f";
com1[2] = "--file";
com1[3] = "-t";
com1[4] = "--text";
if (strcmp(argv[1], com1[1]) == 0) {
cout << com2;
}
}
Array indexs run from
0toN - 1, whereNis the number of elements in the array. Therefore4is an invalid index, and results in undefined behaviour.Ensure the correct number of arguments have been supplied to the program, by checking the value of
argc, before accessing elements inargv.