How can I get argv[] as int?

前端 未结 5 1856
离开以前
离开以前 2020-12-08 09:31

i have a piece of code like this:

int main (int argc, char *argv[]) 
{
   printf(\"%d\\t\",(int)argv[1]);
   printf(\"%s\\t\",(int)argv[1]);
}
5条回答
  •  独厮守ぢ
    2020-12-08 10:28

    argv[1] is a pointer to a string.

    You can print the string it points to using printf("%s\n", argv[1]);

    To get an integer from a string you have first to convert it. Use strtol to convert a string to an int.

    #include    // for errno
    #include   // for INT_MAX
    #include   // for strtol
     
    char *p;
    int num;
    
    errno = 0;
    long conv = strtol(argv[1], &p, 10);
    
    // Check for errors: e.g., the string does not represent an integer
    // or the integer is larger than int
    if (errno != 0 || *p != '\0' || conv > INT_MAX) {
        // Put here the handling of the error, like exiting the program with
        // an error message
    } else {
        // No error
        num = conv;    
        printf("%d\n", num);
    }
    

提交回复
热议问题