How to convert a command-line argument to int?

前端 未结 7 1886
难免孤独
难免孤独 2020-12-01 03:18

I need to get an argument and convert it to an int. Here is my code so far:

#include 


using namespace std;
int main(int argc,int argvx[]) {         


        
相关标签:
7条回答
  • 2020-12-01 04:09

    The approach with istringstream can be improved in order to check that no other characters have been inserted after the expected argument:

    #include <sstream>
    
    int main(int argc, char *argv[])
    {
        if (argc >= 2)
        {
            std::istringstream iss( argv[1] );
            int val;
    
            if ((iss >> val) && iss.eof()) // Check eofbit
            {
                // Conversion successful
            }
        }
    
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题