如何将argv 作为int?

我有一段这样的代码:

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

在shell中我这样做:

./test 7

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

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

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

要从字符串中获取整数,首先要转换它。 使用strtol将字符串转换为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: eg, 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); } 

您可以使用strtol

 long x; if (argc < 2) /* handle error */ x = strtol(argv[1], NULL, 10); 

或者,如果您使用的是C99或更高版本,您可以探索strtoimax

“string to long”( strtol )函数是此标准。 基本用法:

 #include  int arg = strtol(argv[1], NULL, 10); // string to long(string, endptr, base) 

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

 #include  char* p; int arg = strtol(argv[1], &p, 10); if (*p != '\0') // an invalid character was found before the end of the string 

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

 #include  #include  char* p; errno = 0; int arg = strtol(argv[1], &p, 10); if (*p != '\0' || errno != 0) return 1; // Everything went well printf("%d", arg); 

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

你可以使用函数int atoi (const char * str);
您需要包含#include 并以这种方式使用该函数:
int x = atoi(argv[1]);
如果需要,可以在这里获得更多信息: atoi – C ++参考

 /* Input from command line using atoi, and strtol */ #include //printf, scanf #include //atoi, strtol //strtol - converts a string to a long int //atoi - converts string to an int int main(int argc, char *argv[]){ char *p;//used in strtol int i;//used in for loop long int longN = strtol( argv[1],&p, 10); printf("longN = %ld\n",longN); //cast (int) to strtol int N = (int) strtol( argv[1],&p, 10); printf("N = %d\n",N); int atoiN; for(i = 0; i < argc; i++) { //set atoiN equal to the users number in the command line //The C library function int atoi(const char *str) converts the string argument str to an integer (type int). atoiN = atoi(argv[i]); } printf("atoiN = %d\n",atoiN); //-----------------------------------------------------// //Get string input from command line char * charN; for(i = 0; i < argc; i++) { charN = argv[i]; } printf("charN = %s\n", charN); } 

希望这可以帮助。 祝好运!