I'm writing a very basic command line C++ application that takes arguments on execution.
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 floats as parameters (to add them together later), but I can't seem to cast the character arrays as floats.
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).
I'm using the Code::Blocks IDE if that answers any questions.
My code:
#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]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With