0

我将参数传递给 C 程序:

程序名称 1234

int main (int argc, char *argv[]) {

    int     length_of_input = 0;    
    char*   input           = argv[1];


    while(input[length_of_input]) {
        //convert input from array of char to int
        length_of_input++;
    }
}

我希望能够将传递给函数的参数的每个数字单独用作整数。atoi(input[]) 引发编译时错误。

此代码无法编译:

while(input[length_of_input]) {
    int temp = atoi(input[length_of_input]);
    printf("char %i: %i\n", length_of_input, temp);
    length_of_input++;
}
4

4 回答 4

4
int i;
for (i = 0; input[i] != 0; i++){
    output[i] = input[i] - '0';
}
于 2011-04-26T21:52:18.220 回答
1

看到这是家庭作业,你也可以做

output[i] = input[i] - '0';

但要小心它input[i]实际上是一个数字(即它在'0'和之间'9')!

于 2011-04-26T22:00:49.250 回答
1

首先,您必须检查需要为整数数组分配多少空间。这可以通过strlen()函数或遍历字符串并检查找到多少有效字符来完成。然后您必须遍历字符串并将每个(有效)字符转换为等效的整数。这里很难使用函数atoi()scanf()函数族,因为它们除了数组作为输入。更好的解决方案是编写自己的小转换器函数或转换代码段。

这是将字符串转换为整数数组的小示例应用程序。如果字符不是有效的十进制数字,-1则放入数组中。

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

int main(int argc, char *argv[])
{
    int length, i;
    int *array;
    char *input = argv[1];

    /* check if there is input */
    if(input == NULL) return EXIT_FAILURE;

    /* check the length of the input */
    length = strlen(input);
    if(length < 1) return EXIT_FAILURE;

    /* allocate space for the int array */
    array = malloc(length * sizeof *array);
    if(array == NULL) return EXIT_FAILURE;

    /* convert string to integer array */
    for(i = 0; i < length; ++i) {
        if(input[i] >= '0' && input[i] <= '9')
            array[i] = input[i] - '0';
        else
            array[i] = -1; /* not a number */
    }

    /* print results */
    for(i = 0; i < length; ++i)
        printf("%d\n", array[i]);

    /* free the allocated memory */
    free(array);

    return EXIT_SUCCESS;
}

还要检查这些问题:

于 2011-04-26T22:23:20.743 回答
0

您可以测试参数是否是带有 isdigit() 的数字

http://www.cplusplus.com/reference/clibrary/cctype/isdigit/

并使用 atoi 功能。

http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/

并且使用时要小心

char*   input           = argv[1];

将字符串从 argv 复制到输入(使用 malloc 之后),这样会更好。

于 2011-04-26T21:57:44.783 回答