我正在编写一个非常基本的命令行C++应用程序,它在执行时需要参数。
我今天刚开始学习C ++,很明显,您只能将 char **
作为参数的数据类型。我想将两个float
作为参数传递(稍后将它们相加),但似乎无法将字符数组转换为浮点数。
我尝试了使用 static_cast<float>(argv[0])
和 stof(argv[0])
转换这些值,但两者都会导致编译错误(无法转换和未定义,分别)。
如果有任何问题,我正在使用 Code::Blocks IDE
。
我的代码:
#include <iostream>
#include <string>
/**
* author: 2mac
*
*/
using namespace std;
void derp();
float getSum(float num1, float num2);
int main(int argc, char** argv)
{
float num1 = static_cast<float>(argv[0]);
float num2 = static_cast<float>(argv[1]);
if (argc != 0 || argc != 2)
cout << "Usage: hello-world [args]\nargs: none OR <num1> <num2> to be added together" << endl;
else
{
switch (argc)
{
case 0:
derp();
break;
case 2:
derp();
cout << num1 << " + " << num2 << " equals " << getSum(num1,num2) << endl;
break;
}
}
return 0;
}
void derp()
{
cout << "Hello, world!\n";
cout << "It's time to lern some C++!" << endl;
}
float getSum(float num1, float num2)
{
return num1 + num2;
}