命令行参数C ++ [英] Command line parameters c++

查看:85
本文介绍了命令行参数C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已要求我创建一个c ++程序,该程序接受命令行参数并输出小于此值的质数;如果未指定任何参数,则仅输出std::endlstd::cout""

I have been asked to create a c++ program that "accepts a command line parameter and outputs the number of prime numbers less than this value; if no parameter is given, output just std::endl to std::cout"

我知道如何查找素数,但是我不确定命令行参数"是什么以及它如何与工作联系在一起.另外,我认为如果没有给出参数,您只是std::cout << std::endl吗?

I understand how to look up prime numbers but I am unsure what a "command line parameter" is and how it ties into the work. Also, I think if there is no parameter given, you just std::cout << std::endl?

我试图弄清命令行参数是什么,但是找不到任何有意义的资源来实现这种效果.

I have tried to work out what a command line parameter is but cannot find any meaningful resources to this effect.

推荐答案

命令行参数是使用名称传递给程序的参数.例如,UNIX程序cp(复制两个文件)具有以下命令行参数:

Command line arguments are arguments passed to your program with its name. For example, the UNIX program cp (copies two files) has the following command line arguments:

cp SOURCE DEST

您可以使用argcargv访问命令行参数:

You can access the command line arguments with argc and argv:

int main(int argc, char *argv[])
{
    return 0;
}

argc是参数的数量,包括程序名,而argv是包含参数的字符串数组. argv[0]是程序名称,并且保证argv[argc]NULL指针.

argc is the number of arguments, including the program name, and argv is the array of strings containing the arguments. argv[0] is the program name, and argv[argc] is guaranteed to be a NULL pointer.

因此cp程序可以这样实现:

So the cp program can be implemented as such:

int main(int argc, char *argv[])
{
    char *src = argv[1];
    char *dest = argv[2];

    cpy(dest, src);
}

不必将它们命名为argcargv;它们可以有您想要的任何名称,尽管传统上它们被称为该名称.

They do not have to be named argc and argv; they can have any name you want, though traditionally they are called that.

这篇关于命令行参数C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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