在 C 中从 argv 创建整数数组

标签 c arrays argv cs50

很明显,我对此是全新的,但我正在学习 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/

相关文章:

c - 为什么我们将命令名称作为路径和参数列表两次传递给 execve?

Linux编程: Compile code with dependencies

大多数语言的行和列索引约定

php - 将 php 数组传递给 jquery

java - 如何将 Headers EntrySet.forEach 转换为字符串数组?

c++ - 使 argv 成为整数数组

c - 在 C 中,如何将字符串转换为字符数组?

c - 寻找一种算法来找到最短路径

c - array 和 &array 有什么区别?

c - C 中 header 定义结构的 main 中的语句错误