Checking argv[] against a string? (C++)

前端 未结 5 736
情歌与酒
情歌与酒 2020-12-28 15:05

So I\'m attempting to check the arguments that I\'m inputting into my program, and one of them is either the word \"yes\" or \"no\", entered without the quotes.

I\'

5条回答
  •  鱼传尺愫
    2020-12-28 15:36

    Modern C++, with a bit of const correctness...

    /*BINFMTCXX: -Wall -Werror -std=c++17
    */
    
       #include 
       #include 
       #include 
       using std::string; using std::vector; using std::cerr;
    
    int main( int argc, char * const argv[] )
       {
       assert( argc >= 1 ); // exploratory -- could fail in principle, but not really
       const vector args(argv+1,argv+argc); // convert C-style to modern C++
       for ( auto a : args ) cerr<<(a=="yes")<<"\n"; // operator '==' works as expected
       }
    

    Note: The standard doesn't guarantee that you can use const in the signature of main, nor does it forbid it.

    As used here, const ensures that we won't change things we don't intend to change -- which is the purpose of const in the C++ language.

    See also...

    • Passing argv as const
    • What is the proper declaration of main?
    • int getopt(int argc, char * const argv[], const char *optstring) -- notice signature
    • What does int argc, char *argv[] mean? -- min value of argc

提交回复
热议问题