Convert all and any command line input to string in C++ -
i trying write small code @ beginning of program runs different functions depending on file extension of files passed when calling program command line.
i want convert argv[2]
string (called st
) can compare ".png"
, ".txt"
, etc. using strccmp
.
i found similar solutions around so, none of them addressed issue of saving argument string variable. whenever try use argv[1]
or argv[2]
, debugger complains subscript out of range, , @ loss how around this.
int main(int argc, char** argv) { // first , simplest attempt sd::string st = argv[2]; // second attempt fails std::vector<std::string> all_arg; if (argc > 1) { all_arg.assign(argv + 1, argv + argc); } std::string st = all_arg[2]; // comparison st = st.substr(st.size() - 4, st.size() - 1); if (strcmp(st.c_str(), ".png")) { ... } else {...} }
corrected obvious problems, code compiles , runs fine.
#include <iostream> #include <vector> #include <string> int main( int argc, char ** argv ) { std::vector< std::string > all_arg; if ( argc > 1 ) { all_arg.assign( argv + 1, argv + argc ); } ( auto str : all_arg ) { std::cout << str << "\n"; } }
as comparison, looks fishy in more 1 way...
st = st.substr(check.size() - 4, check.size() - 1);
aside check
not being defined, happens if string shorter 4 characters...?
if (strcmp(st.c_str(), ".png")) { ... }
err... degrading string
char array through c_str()
, going through c function strcmp()
? for?
try this:
for ( auto str : all_arg ) { std::string extension; std::string::size_type length = str.length(); if ( length >= 4 ) { extension = str.substr( size - 4 ); } if ( extension == ".png" ) { std::cout << str << "is png!\n"; } }
and think above being case-sensitive, , once think converting str
lowercase prior comparing, consider locale, might include unicode. ;-)
Comments
Post a Comment