如何在turbo c ++中将整数作为命令行参数传递

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1395057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:50:33  来源:igfitidea点击:

How to pass an integer as command line argument in turbo c++

c++command-lineturbo-c++

提问by Traveling Tech Guy

I am unable to pass integer value through the command line in turbo c++. Please help me.

我无法通过 turbo c++ 中的命令行传递整数值。请帮我。

回答by Kirill V. Lyadvinsky

You can pass arguments to executable only as strings. You could use std::atoito convert string to integer.

您只能将参数作为字符串传递给可执行文件。您可以使用std::atoi将字符串转换为整数。

int main(int argc, const char* argv[])
{
  if ( argc > 1 ) {
    int i = atoi( argv[1] );
  }

  return 0;
}

回答by Jon Skeet

You'll have to pass it through as a string, and then parse it with something like atoior strtol.

您必须将其作为字符串传递,然后使用类似atoistrtol.

Command line arguments are always strings (or char*s if you want to be picky :)

命令行参数始终是字符串(char*如果您想挑剔,则为 s :)

回答by Traveling Tech Guy

You cannot pass integers from the command line, only strings. Pass in your number, and use ::atoi(or any other conversion function) to convert it to an integer

您不能从命令行传递整数,只能传递字符串。传入您的数字,并使用::atoi(或任何其他转换函数)将其转换为整数

回答by Traveling Tech Guy

I really wonder why you are still sticking to the ancient compiler! The sooner you switch to modern compilers the better it is! Anyways the code for doing that is below:

我真的很奇怪你为什么还坚持使用古老的编译器!越早切换到现代编译器越好!无论如何,这样做的代码如下:

#include<stdlib.h>
#include<iostream.h>
int main(int lenArgs, char *args[]){
    int num = 0;
    if (lenArgs > 1){
        num = atoi(args[1]);
    }
    else{
        cout<<"Please give an argument to the program!";
        return 1;
    }
    cout<<num<<endl;
    return 0;
}

回答by xtofl

If you're passing it in just for this one time, and you don't need to maintain the parameters you can give your main function, you can convert the char*parameters the C++ runtime provides your program with by using int i = atoi( argv[1] ).

如果您只是为了这一次传入它,并且不需要维护可以提供给 main 函数的char*参数,则可以使用int i = atoi( argv[1] ).

If you're going to have more parameters, you probably want some way to name them, too. Then it's worth taking a look at the getoptfunction. This one allows for more flexible command line parameters.

如果您要拥有更多参数,您可能还需要某种方式来命名它们。那么值得一看的getopt功能。这个允许更灵活的命令行参数。

There even are command-line parsing frameworks out there that allow for type-checking and the lot.

甚至还有命令行解析框架可以进行类型检查和大量检查。