如何将包含作为命令行参数传递的整数的字符串转换为整数数组

时间:2015-08-09 14:48:52

标签: c command-line-arguments

./ a.out" 1 23 5 7 2 21" 我想将上面作为命令行参数传递的字符串转换为C编程中的整数数组。非常感谢帮助。

谢谢。

3 个答案:

答案 0 :(得分:0)

一个简单的循环可以解决你的问题 -

int a[argc];

for(i = 0; i < argc; i++)
{
      a[i] = atoi(argv[i+1]);
}

答案 1 :(得分:0)

如果传递字符串

./ a.out" 1 23 5 7 2 21&#34;

你需要在传递&#34; int&#34;时对字符串进行标记化。值为数组(应该是动态的),因为您传递的是字符串而不是多个选项。 (这是我最初的想法,但改变了)

#include <stdio.h>
#include <stdlib.h>
#include <string.h> /* For strtok */


int main( int argc, char **argv )
{
   int i = 0;
   int *intArray;
   const char s[2] = " ";
   char *token;

   token = strtok(argv[1], s);

   intArray = malloc(sizeof(int));
   while( token != NULL )
   {
      intArray[i++] = atoi(token);
      token = strtok(NULL, s);
   }

    //intArray holds the values but this is to display the results
    int j;
    for (j=0; j < i ; j++){
        printf( " %d\n", intArray[j] );
    }
    return 0;
}

如果传递多个选项(在程序名称之后)

./ a.out 1 23 5 7 2 21

    int i;
    int intArray[argc-1];
    for (i=0; i < argc - 1; i++){
        intArray[i] = atoi(argv[i+1]);
    }
    return 0;

答案 2 :(得分:-1)

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

int main(int argc, char *argv[]){
    if(argc != 2){
        exit(EXIT_FAILURE);
    }
    int n = 0;//number of elements
    char prev = ' ', *s = argv[1];
    while(*s){
        if(isspace(prev) && !isspace(*s))
            ++n;
        prev = *s++;
    }
    int nums[n];
    char *endp;
    s = argv[1];
    for(int i = 0; i < n; ++i){
        nums[i] = strtol(s, &endp, 10);
        s = endp;
        printf("%d\n", nums[i]);//check print
    }
    return 0;
}