lov*_*eed 6 c++ command-line-arguments
我有一个C++程序,我运行了很多参数值.我想做的是以下内容:假设我有两个参数:
int main(){
double a;
double b;
//some more lines of codes
}
Run Code Online (Sandbox Code Playgroud)
在我编译之后,我想将其运行为
./output.out 2.2 5.4
Run Code Online (Sandbox Code Playgroud)
因此a取值2.2并b取值5.4.
当然有一种方法是使用,cin>>但我不能这样做因为我在集群上运行程序.
das*_*ght 20
你需要使用命令行参数在main:
int main(int argc, char* argv[]) {
if (argc != 3) return -1;
double a = atof(argv[1]);
double b = atof(argv[2]);
...
return 0;
}
Run Code Online (Sandbox Code Playgroud)
此代码使用以下方法解析参数atof; 你可以stringstream改用.
Ed *_* S. 11
如果你想使用命令行参数,那么不,你不要使用,cin因为它为时已晚.您需要将main签名更改为:
int main(int argc, char *argv[]) {
// argc is the argument count
// argv contains the arguments "2.2" and "5.4"
}
Run Code Online (Sandbox Code Playgroud)
所以你现在有argv一个指针数组char,每个指针指向一个被传递的参数.第一个参数通常是可执行文件的路径,后续参数是在启动应用程序时以指针形式传递的内容char.
在这种情况下,您需要将char*s 转换为doubles.