Dozar
Dozar

Reputation: 71

How to convert user input char to Double C++

I'm trying to figure out a method of taking a user input character and converting it to a double. I've tried the atof function, though it appears that can only be used with constant characters. Is there a way to do this at all? Heres an idea of what I'd like to do:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>

int main(){

    char input;
    double result;

    cin >> input; 

    result = atof(input);
}

Upvotes: 0

Views: 31877

Answers (3)

vsoftco
vsoftco

Reputation: 56547

Here is a way of doing it using string streams (btw, you probably want to convert a std::string to a double, not a single char, since you lose precision in the latter case):

#include <iostream>
#include <sstream>
#include <string>

int main()
{
    std::string str;
    std::stringstream ss;
    std::getline(std::cin, str); // read the string
    ss << str; // send it to the string stream

    double x;
    if(ss >> x) // send it to a double, test for correctness
    {
        std::cout << "success, " << " x = " << x << std::endl;
    }
    else
    {
        std::cout << "error converting " << str << std::endl;
    }
}

Or, if your compiler is C++11 compliant, you can use the std::stod function, that converts a std::string into a double, like

double x = std::stod(str);

The latter does basically what the first code snippet does, but it throws an std::invalid_argument exception in case it fails the conversion.

Upvotes: 0

ohannes
ohannes

Reputation: 514

Replace

char input

with

char *input

Upvotes: -1

user4098326
user4098326

Reputation: 1742

atof converts a string(not a single character) to double. If you want to convert a single character, there are various ways:

  • Create a string by appending a null character and convert it to double
  • Subtract 48(the ASCII value of '0') from the character
  • Use switch to check which character it is

Note that the C standard does not guarantee the character codes are in ASCII, therefore, the second method is unportable, through it works on most machines.

Upvotes: 4

Related Questions