我怎样才能将argv []作为int?

Mic*_*ael 29 c

我有一段这样的代码:

int main (int argc, char *argv[]) 
{
   printf("%d\t",(int)argv[1]);
   printf("%s\t",(int)argv[1]);
}
Run Code Online (Sandbox Code Playgroud)

在shell中我这样做:

./test 7

但是第一个printf结果不是7,我怎样才能将argv []作为int?非常感谢

oua*_*uah 34

您的代码调用未定义的行为(UB),在您的情况下,它会导致分段错误.

argv[1] 是一个指向字符串的指针.

您可以使用以下方式打印: printf("%s\n", argv[1]);

要从字符串中获取整数,首先要转换它.使用strtol一个字符串转换为一个int.

#include <errno.h>   // for errno
#include <limits.h>  // for INT_MAX
#include <stdlib.h>  // 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);
}
Run Code Online (Sandbox Code Playgroud)

  • strtol函数中的10是什么意思? (4认同)
  • @AlejandroSazo它是转换的基础,所以这里转换是在基础'10`中完成的. (4认同)
  • @BryanGreen `atoi()` 不应该被使用,因为使用这样的函数不可能检测到错误。 (3认同)
  • num = atoi(argv[1]) 更简单。 (2认同)

Luc*_*Luc 17

"string to long"(strtol)函数是此标准.基本用法:

#include <stdlib.h>

long arg = strtol(argv[1], NULL, 10);
// string to long(string, endpointer, base)
Run Code Online (Sandbox Code Playgroud)

由于我们使用十进制系统,因此base为10. endpointer参数将被设置为"第一个无效字符",即第一个非数字.如果您不在乎,请将参数设置为NULL而不是传递指针.如果您不希望出现非数字,则可以确保将其设置为"null终止符"(\0终止C中的字符串):

#include <stdlib.h>

char* p;
long arg = strtol(argv[1], &p, 10);
if (*p != '\0') // an invalid character was found before the end of the string
Run Code Online (Sandbox Code Playgroud)

正如手册页所提到的,您可以使用errno检查没有发生错误(在这种情况下溢出或下溢).

#include <stdlib.h>
#include <errno.h>

char* p;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &p, 10);
if (*p != '\0' || errno != 0) {
    return 1; // In main(), returning non-zero means failure
}

// Everything went well, print it as 'long decimal'
printf("%ld", arg);
Run Code Online (Sandbox Code Playgroud)

除此之外,您还可以实现自定义检查:测试用户是否完全通过了参数; 测试数字是否在允许的范围内; 等等


cni*_*tar 13

你可以用strtol它:

long x;
if (argc < 2)
    /* handle error */

x = strtol(argv[1], NULL, 10);
Run Code Online (Sandbox Code Playgroud)

或者,如果你使用的是C99或更好,你可以探索strtoimax.


Ang*_*ano 5

您可以使用该功能int atoi (const char * str);
您需要以#include <stdlib.h>这种方式包含和使用该函数:
int x = atoi(argv[1]);
如果需要,请查看更多信息:atoi - C++ 参考