[英]C++ - accepting command line arguments?
So this was my original code: 所以这是我的原始代码:
#include <iostream>
using namespace std;
int main ()
{
float x;
cout << "Please enter an integer value: ";
cin >> x;
if ((x >= 100) && (x < 200)) {
cout << "split";
} else if (x == 0 ||x == 1 ) {
cout << "steal";
} else {
cout << "split";
}
system("pause");
}
It works perfectly, but I need it to run this way: 它工作得很好,但我需要它以这种方式运行:
C:\> program.exe 109
it will read 109
and give the output - "steal"
. 它将读取
109
并给出输出 - "steal"
。
C:\> program.exe 0.5
it will read 0.5
and give me the output "split"
. 它会读
0.5
并给我输出"split"
。
What do I have to add to my original code to do this? 我需要添加到原始代码中才能执行此操作?
Change your main to 将主要内容更改为
int main (int argc, char** argv)
The you can check number of specified parameters to your program in argc
and the values (as char *
) in argv
. 您可以在
argc
检查程序的指定参数数量,并在argv
检查值(作为char *
)。 You can convert that values to float using std::stof
您可以使用
std::stof
将该值转换为float
float x = 0.0f;
if (argc > 1) {
x = std::stof(argv[1]);
} else {
std::cerr << "Not enough arguments\n";
return 1;
}
Please note that the first argument to the program is the name of the executable itself ( program.exe
in your case), so you need to check for at least two arguments. 请注意,程序的第一个参数是可执行文件本身的名称(在您的情况下为
program.exe
),因此您需要检查至少两个参数。
References: http://en.cppreference.com/w/cpp/string/basic_string/stof 参考文献: http : //en.cppreference.com/w/cpp/string/basic_string/stof
you can do this by using command line arguments. 您可以使用命令行参数执行此操作。 Here is format for main function:
这是main函数的格式:
int main (int argc, _TCHAR* argv[])
{
}
Here argc
represents number of arguments(returns 2 in your case, program.exe 0.5 ) 这里
argc
表示参数的数量(在你的情况下返回2,program.exe 0.5)
argv
represents two strings. argv
代表两个字符串。 1st containing program.exe
and second containing 0.5
. 第一个包含
program.exe
,第二个包含0.5
。
This way you can solve you problem 这样你就可以解决你的问题
Can we have more clarity on the question? 我们能否更清楚地解决这个问题? Do you want to know how to execute the code using command line arguments?
您想知道如何使用命令行参数执行代码吗? In that case here it is:
在这种情况下,它是:
int main (int no_of_args, char* arglist[])
{
}
In argList
, the first item holds the name of the executable and subsequent items hold the inputs provided. 在
argList
,第一个项目包含可执行文件的名称,后续项目保存所提供的输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.