从C中的argv创建一个整数数组

时间:2017-03-28 21:31:27

标签: c arrays argv cs50

很明显,我对此很陌生,但我正在参加CS50课程,而且我很难完成其中一项任务。我认为这很简单,但我的语法中存在一些缺陷导致运行时错误。 我正在尝试使用命令行参数中的每个字符创建一个数组作为数组的元素,但我尝试的任何东西似乎都无法工作。这是绊倒我的大块:

#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]);
     }
}

所以,我知道这确实是错的,但是有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:1)

我不确定我是否正确地理解了你想要做什么,但是如果你只想从你的程序参数中给出的数字中提取每一个构成它的数字,你就可以这样做

#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]);
        }
     }
}