问题描述
我正在编写一个非常基本的命令行C ++应用程序,该应用程序在执行时会接受参数.
I'm writing a very basic command line C++ application that takes arguments on execution.
我今天才刚开始使用C ++,看来您只能将 char **
作为参数的数据类型.我想将两个 float
用作参数(稍后再将它们添加在一起),但是我似乎无法将字符数组转换为浮点型.
I just started C++ today, and it seems apparent that you can only take char**
as the data type for arguments. I want to take two float
s as parameters (to add them together later), but I can't seem to cast the character arrays as floats.
我尝试了 static_cast< float>(argv [0])
和 stof(argv [0])
来强制转换值,并且都给出了编译器错误(无法分别进行强制转换和未在范围内定义).
I have tried static_cast<float>(argv[0])
and stof(argv[0])
to cast the values, and both give compiler errors (unable to cast and not defined in scope, respectively).
如果正在回答任何问题,我正在使用 Code :: Blocks IDE
.
I'm using the Code::Blocks IDE
if that answers any questions.
我的代码:
#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;
}
推荐答案
使用此方法将您的输入转换为浮点数,
Using this to convert your input to float number,
double f1, f2;
if (argc == 2)
{
f1 = atof (argv[0]);
f2 = atof (argv[1]);
}
这篇关于将字符数组转换为浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!