在命令行中输入(Input from command line)

2019-07-30 05:28发布

我有C ++,其余为参数的许多值运行程序。 我想要做的是以下几点:比方说,我有两个参数:

int main(){
    double a;
    double b;
//some more lines of codes
}

现在我编译后后,我要运行它

./output.out 2.2 5.4

这样a取值2.2和b取值5.4。

当然,一个方法是使用cin>>但我不能这样做,因为我运行一个集群上的程序。

Answer 1:

你需要使用命令行参数在你的main

int main(int argc, char* argv[]) {
    if (argc != 3) return -1;
    double a = atof(argv[1]);
    double b = atof(argv[2]);
    ...
    return 0;
}

此代码解析使用参数atof ; 你可以使用stringstream来代替。



Answer 2:

如果要使用命令行参数则没有,你使用cin ,因为它是为时已晚。 你需要改变你的main签名:

int main(int argc, char *argv[]) {
    // argc is the argument count
    // argv contains the arguments "2.2" and "5.4"
}

所以,你现在拥有argv是指针数组char ,每个指针指向已传递的参数。 第一个参数是典型路径到您的可执行文件,后面的参数是什么,当你应用程序的启动中传递,在指针的形式char

你将需要转换char*的,以double在这种情况下秒。



Answer 3:

这就是命令行参数是:

#include <sstream>

int main(int argc, char *argv[])
{
    if (argv < 3)
       // show error
    double a, b;

    std::string input = argv[1];
    std::stringstream ss = std::stringstream(input);

    ss >> a;

    input = argv[2];
    ss = std::stringstream(input);

    ss >> b;

    // a and b are now both successfully parsed in the application
}


Answer 4:

你看着提升程序选项 ?

这将需要在命令行参数,像许多其他的建议,让你提供一个非常一致的,清洁的和可扩展的命令行界面。



Answer 5:

您可以使用的这种形式main()函数来获取命令行参数

    int main(int argc, char* argv[]) { 

    } 

当值argv[]数组包含您的命令行变量char* ,你将需要转换为floatsdoubles在您的情况



文章来源: Input from command line