如何在阵列中存储argv命令行输入(C) [英] How do I store argv command line inputs in an array (C)

查看:86
本文介绍了如何在阵列中存储argv命令行输入(C)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试将argv命令行输入输入到数组中。

所有打印输出的是内存位置而不是argv输入



我尝试过:



Trying to input the argv command line inputs into an array.
All it's printing out is the memory location and not the argv inputs

What I have tried:

#define MAX 12

int main(int argc, char* argv[])
{
  char* argv_inputs[MAX];
  int array_of_ints[MAX];
  int i, size = argc;

  for(i = 2; i <= argc; i++)
  {
    argv_inputs[i] = argv[i];
    printf("%d ", argv_inputs[i]);
  }

推荐答案

您不需要 argv 输入数组但必须使用 atoi - C ++ Reference 将文本参数转换为数字[ ^ ]或 strtol - C ++参考 [ ^ ]:

You don't need a copy of the argv input array but have to convert the textual arguments to numbers using atoi - C++ Reference[^] or strtol - C++ Reference[^] :
int main(int argc, char* argv[])
{
    int array_of_ints[MAX];
    int i;
    
    for (i = 1; i < argc && i < MAX; i++)
    {
        array_of_ints[i] = atoi(argv[i]);
        printf("%d ", array_of_ints[i]);
    }
    return 0;
}

请注意,上面没有检查输入是否是有效数字并且我已经更正了循环。使用C / C ++,数组从索引零开始,因此最后一项由 size - 1 访问。



我还添加了一张支票,以确保不会发生越界访问。

[/ EDIT]

Note that the above does not check if the input is a valid number and that I have corrected the loop. With C/C++, arrays start at the index zero and the last item is therefore accessed by size - 1.

I have also added a check to ensure that no out-of-bound accesses occur.
[/EDIT]


输入是一个指向char的指针数组,并将它们分配给整数数组。这是行不通的:虽然指针是整数值(或64位应用程序中的长整数值,数字本身是没有意义的 - 它们是每个字符串中第一个字符的地址,所以当你打印它们时你得到的数字是完全没有意义。

试试这个:

The input is an array of pointer-to-char values, and you are assigning them to an array of integers. That won't work: while the pointers are integer values (or long integer values in a 64 bit application, the numbers themselves are meaningless - they are the addresses of the first character in each string, so when you print them you get numbers which make no sense at all.
Try this:
int main(int argc, char* argv[])
    {
    int i;
    for(i = 2; i < argc; i++)
        {
        printf("%s\n", argv[i]);
        }
    }

这将打印输入。


这篇关于如何在阵列中存储argv命令行输入(C)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆