我有一段这样的代码:
int main (int argc, char *argv[])
{
printf("%d\t",(int)argv[1]);
printf("%s\t",(int)argv[1]);
}
在外壳中我这样做:
./test 7
但第一个 printf 结果不是 7,我怎样才能得到 argv[] 作为 int ?非常感谢
argv[1]
是一个指向字符串的指针。
您可以使用打印它指向的字符串printf("%s\n", argv[1]);
要从字符串中获取整数,您必须首先对其进行转换。使用strtol
将字符串转换为int
.
#include <stdio.h>
#include <errno.h> // for errno
#include <limits.h> // for INT_MAX, INT_MIN
#include <stdlib.h> // for strtol
int main(int argc, char *argv[])
{
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 || conv < INT_MIN) {
// Put here the handling of the error, like exiting the program with
// an error message
} else {
// No error
num = conv;
printf("%d\n", num);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)