很明显,我对此是全新的,但我正在学习 CS50 类(class),并且我在一项作业上遇到了困难。我认为这很简单,但我的语法中存在一些缺陷,导致运行时错误。 我正在尝试使用命令行参数中的每个字符作为数组的元素来创建一个数组,但我尝试的任何操作似乎都不起作用。这是让我困惑的部分:
#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, string argv[])
{
//make sure only 2 command line arguments entered
if( argc != 2)
{
printf("Please input a keyword composing of letters only\n");
return 1;
}
else
{
// declare variable "m" to designate the number of elements in the array "keyword"
int m = strlen(argv[1]);
//array declaration for "keyword" with "m" elements
int keyword[m];
//convert characters to integers
keyword[m] = atoi(argv[1]);
//iterate through characters in argv[1] in order to printf the elements in the array
for (int j = 0; j < strlen(argv[1]); j++)
printf("%i",keyword[j]);
}
}
所以,我知道这确实是错误的,但有人能指出我正确的方向吗?
最佳答案
我不确定我是否正确理解了你想要做什么,但是如果你只想从程序参数中给出的数字中提取组成它的每个数字,你可以这样做
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char** argv)
{
//make sure only 2 command line arguments entered
if( argc != 2)
{
printf("Please input a keyword composing of letters only\n");
return 1;
}
else
{
// declare variable "m" to designate the number of elements in the array "keyword"
int m = strlen(argv[1]);
//array declaration for "keyword" with "m" elements
int keyword[m];
//convert characters to integers
//iterate through characters in argv[1] in order to printf the elements in the array
for (int j = 0; j < strlen(argv[1]); j++){
keyword[j] = argv[1][j] - '0';
printf("%d\n",keyword[j]);
}
}
}
关于在 C 中从 argv 创建整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43080319/