Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/.htaccess/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何将包含作为命令行参数传递的整数的字符串转换为整数数组_C_Command Line Arguments - Fatal编程技术网

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

C 如何将包含作为命令行参数传递的整数的字符串转换为整数数组,c,command-line-arguments,C,Command Line Arguments,./a.out“12355721” 我想将上面作为命令行参数传递的字符串转换为C编程中的整数数组。非常感谢你的帮助 多谢各位 一个简单的循环可以解决您的问题- int a[argc]; for(i = 0; i < argc; i++) { a[i] = atoi(argv[i+1]); } inta[argc]; 对于(i=0;i

./a.out“12355721” 我想将上面作为命令行参数传递的字符串转换为C编程中的整数数组。非常感谢你的帮助


多谢各位

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

int a[argc];

for(i = 0; i < argc; i++)
{
      a[i] = atoi(argv[i+1]);
}
inta[argc];
对于(i=0;i
如果传递字符串 /a.out“12355721”

在将“int”值传递给数组(应该是动态的)时,需要对字符串进行标记,因为传递的是字符串而不是多个选项。(这是我最初的想法,但后来改变了)

#包括
#包括
#包括/*用于strtok*/
int main(int argc,字符**argv)
{
int i=0;
int*intArray;
常量字符s[2]=“”;
字符*令牌;
令牌=strtok(argv[1],s);
intArray=malloc(sizeof(int));
while(令牌!=NULL)
{
intArray[i++]=atoi(令牌);
令牌=strtok(空,s);
}
//intArray保留这些值,但这是为了显示结果
int j;
对于(j=0;j
如果传递多个选项(在程序名之后) /a.out 12355721

    int i;
    int intArray[argc-1];
    for (i=0; i < argc - 1; i++){
        intArray[i] = atoi(argv[i+1]);
    }
    return 0;
inti;
int intArray[argc-1];
对于(i=0;i
#包括
#包括
#包括
int main(int argc,char*argv[]){
如果(argc!=2){
退出(退出失败);
}
int n=0;//元素数
char prev='',*s=argv[1];
而(*s){
如果(isspace(上一个)和&!isspace(*s))
++n;
prev=*s++;
}
整数单位[n];
char*endp;
s=argv[1];
对于(int i=0;i
“我已经尝试了很多方法,但是没有一种有效。”--请给我们展示一下。
strtok()
atoi()
的一点魔力。请提供一个。@LightnessRacesinOrbit很抱歉我没有理解你。可以使用
int n=0;对于(n=0;;++n){strtol(s,&endp,10);s=endp;}
来计算
n
来解析与第二遍完全相同的内容。
    int i;
    int intArray[argc-1];
    for (i=0; i < argc - 1; i++){
        intArray[i] = atoi(argv[i+1]);
    }
    return 0;
#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;
}