C语言 如何将argv[]转换为int?

gc0ot86w  于 2022-12-03  发布在  其他
关注(0)|答案(5)|浏览(1317)

我有一段这样的代码:

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

在shell中,我执行以下操作:
./test 7
但是第一个printf的结果不是7,我怎么才能得到argv[]作为一个整数呢?非常感谢

5anewei6

5anewei61#

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);
    }
}
eblbsuwk

eblbsuwk2#

这个问答是关于普通的C,而不是C++。(我不知道C++的答案是否不同,但是你可能需要包括cstring之类的内容。)

基本用法

“string to long”(strtol)函数是标准的(“long”可以容纳比“int”大得多的数字)。

#include <stdlib.h>

long arg = strtol(argv[1], NULL, 10);
// string to long(string, endpointer, base)

因为我们使用十进制系统,基数是10。endpointer参数将被设置为“第一个无效字符”,即第一个非数字。如果你不在乎,将参数设置为NULL,而不是传递一个指针,如图所示。

错误检查(1)

如果不希望出现非数字字符,则应确保将其设置为“null terminator,”因为在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

错误检查(2)

正如man page所提到的,可以使用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);

错误检查(3)

正如sigjuice所指出的,该函数会很高兴地忽略空字符串,并且不会设置errno。我们的空字节检查也不会触发,因为零长度字符串的开头就有一个\0。因此,我们需要另一个导入和另一个检查:

#include <string.h>

if (strlen(argv[1]) == 0) {
    return 1; // empty string
}

转换为整数

所以现在我们只能使用long,但是我们经常需要使用整数。要将long转换为int,我们首先要检查这个数是否在int的有限容量内。为此,我们添加了第二个if语句,如果它匹配,我们就可以将其强制转换。

#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include <string.h>
#include <stdio.h>

if (strlen(argv[1]) == 0) {
    return 1; // empty string
}
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
}

if (arg < INT_MIN || arg > INT_MAX) {
    return 1;
}
int arg_int = arg;

// Everything went well, print it as a regular number
printf("%d", arg_int);

要了解如果不执行此检查会发生什么情况,请在不使用INT_MIN/MAX if语句的情况下测试代码。(231),它将溢出并变为负数。或者如果传递小于-2147483648的数字(-231-1),则它将下溢并变为正值。超出这些限制的值太大,无法容纳在整数中。

完整示例

#include <stdio.h>  // for printf()
#include <stdlib.h> // for strtol()
#include <errno.h>  // for errno
#include <limits.h> // for INT_MIN and INT_MAX
#include <string.h>  // for strlen

int main(int argc, char** argv) {
    if (strlen(argv[1]) == 0) {
        return 1; // empty string
    }
    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
    }

    if (arg < INT_MIN || arg > INT_MAX) {
        return 1;
    }
    int arg_int = arg;

    // Everything went well, print it as a regular number plus a newline
    printf("Your value was: %d\n", arg_int);
    return 0;
}

在Bash中,您可以使用以下命令对此进行测试:

cc code.c -o example  # Compile, output to 'example'
./example $((2**31-1))  # Run it
echo "exit status: $?"  # Show the return value, also called 'exit status'

使用2**31-1时,它应该打印数字和0,因为231-1正好在范围内。如果您传递2**31(没有-1),它将不会打印数字,退出状态将为1
除此之外,还可以实现自定义检查:测试用户是否传递了参数(检查argc),测试数字是否在所需的范围内,等等。

vuktfyat

vuktfyat3#

您可以使用strtol来执行此操作:

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

x = strtol(argv[1], NULL, 10);

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

hpxqektj

hpxqektj4#

您可以使用函数int atoi (const char * str);
您需要包含#include <stdlib.h>,并以下列方式使用函式:
int x = atoi(argv[1]);
如有需要,请参阅以下详细信息:atoi - C++ Reference

2izufjch

2izufjch5#

/*

    Input from command line using atoi, and strtol 
*/

#include <stdio.h>//printf, scanf
#include <stdlib.h>//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); 

}

希望这对你有帮助,祝你好运!

相关问题