Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert character array to float?

Tags:

c++

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;
}
like image 812
2mac Avatar asked Nov 01 '25 03:11

2mac


1 Answers

Using this to convert your input to float number,

double f1, f2;
if (argc == 2)
{
    f1 = atof (argv[0]);
    f2 = atof (argv[1]);
}
like image 70
Deidrei Avatar answered Nov 02 '25 19:11

Deidrei