Pregunta

I'm newbie in C/C++ languages and I want to ask one simple question. I've written the following code:

#include <stdio.h>
#include <math.h>

int main(int argc, char ** argv){
    printf("Square root from %f is %f", argv[1], sqrt(argv[1]));
}

But it doesn't work because argv[1] has type char*. How can I cast argv[1] to double and if it's impossible throw an exception?

¿Fue útil?

Solución

The easiest solution is to use atof. Therefore, you would be writing something like this:

printf("Square root from %s is %f", argv[1], sqrt(atof(argv[1])));

Of course, you could look into higher-level alternatives like C++11's std::stod, but it would be an overkill for this simple case, but if you insist on using C++ code later, I would write this if I were you:

std::string myString = argv[1];
std::cout << "Square root from " << argv[1] << " is "
          << std::sqrt(std::stod(myString)) << std::endl;

You would also need to change the first placeholder to %s because you are printing the first argument in there, which is as you wrote a string.

In your final code, please also make sure that argc is at least 2 before trying to access the second item of the string array.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top