How to convert a command-line argument to int?

前端 未结 7 1935
难免孤独
难免孤独 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 03:53

    Note that your main arguments are not correct. The standard form should be:

    int main(int argc, char *argv[])
    

    or equivalently:

    int main(int argc, char **argv)
    

    There are many ways to achieve the conversion. This is one approach:

    #include 
    
    int main(int argc, char *argv[])
    {
        if (argc >= 2)
        {
            std::istringstream iss( argv[1] );
            int val;
    
            if (iss >> val)
            {
                // Conversion successful
            }
        }
    
        return 0;
    }
    

提交回复
热议问题