I'm fairly new to cpp and I am trying to do a project. It says that the code must take in a filename as an argument and will be run by:
./main -i filename
I have written a for-loop that will iterate through the list of arguments to find the "-i" argument so that I can determine the filename. But this line always return false:
argv[i] == "-i"
Below is my code:
#include <string>
#include <iostream>
int main(int argc, char *argv[]) {
std::string test = argv[0];
for(int i = 0; i < argc; i++){
if(argv[i] == "-i"){
test = argv[i+1];
break;
}
}
std::cout << test;
return 1;
}
You cannot compare pointers to
char
to string literals (char const*
) using==
. Usestd::strcmp()
(<cstring>
) or construct astd::string
(<string>
) from it to make it comparable to achar*
using==
.In the line above you compare two pointers:
char*
andconst char*
, respectively.In other words, instead of comparing
argv[i]
and"-i"
two pointers are compared which are pretty much unlikely to point to the same location. As a result, the check doesn't work in your case.You can fix it in multiple ways, for example wrap
"-i"
intostd::string
to make the comparison work properly:Starting with C++17 you might also use a
std::string_view
:which is a preferable way as it avoids a
std::string
creation.try this: