这是我的代码的一部分:
int main(int argc, char*argv[])
{
//This section shows the statistic of the program
int a;
printf("The number of arguments is :%d \n", argc);
for(a=0; a<argc; a++)
{
printf("argc %d is %s \n",a, argv[a]);
}
根据上面的代码,第二个命令行参数 argv[1] 将是一个 .txt 文件。
第三个命令行参数 argv[2] 将作为字符串输入,例如“monkey”。
我需要知道如何将第二个命令行参数“monkey”存储为单个字符的数组,因此它看起来像这样:
char key[6];
key[0]= 'm';
key[1]= 'o';
key[2]= 'n';
key[3]= 'k';
key[4]= 'e';
key[5]= 'y';
最佳答案
试试这个:
#include <stdio.h>
#include <string.h>
int main(int argc, char*argv[])
{
//This section shows the statistic of the program
int a;
printf("The number of arguments is :%d \n", argc);
for(a=0; a<argc; a++)
{
printf("argc %d is %s \n",a, argv[a]);
}
size_t len = strlen(argv[2]);
int key[10];
int i = 0;
for(i = 0; i < len; i++)
{
key[i] = argv[2][i];
}
for (i = 0; i < len; i++)
{
printf("key[%d] = %c\n", i, key[i]);
}
}
关于C语言: How do I convert a string parameter from a command line into an array of individual characters?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39803048/