作者:popou | 来源:互联网 | 2023-10-10 20:38
所以这是我的原始代码:
#include
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");
}
它工作得很好,但我需要它以这种方式运行:
C:\> program.exe 109
它将读取109并给出输出 – “偷”.
C:\> program.exe 0.5
它会读0.5并给我输出“分裂”.
我需要添加到原始代码中才能执行此操作?
解决方法:
将主要内容更改为
int main (int argc, char** argv)
您可以在argc中检查程序的指定参数数量,并在argv中检查值(作为char *).您可以使用std :: stof将该值转换为float
float x = 0.0f;
if (argc > 1) {
x = std::stof(argv[1]);
} else {
std::cerr <<"Not enough arguments\n";
return 1;
}
请注意,程序的第一个参数是可执行文件本身的名称(在您的情况下为program.exe),因此您需要检查至少两个参数.
参考文献:http://en.cppreference.com/w/cpp/string/basic_string/stof