1

I'm trying to convert the string variable passed by reference to a decimal. When I put in a string in quotes using atoi it works, but not with a string variable. What should I do instead?

void stringDecision(string& assembledString) {

double convertedString; // conversion to double

// remove unary + operator because it's unnecessary
if (assembledString[0] == '+' && assembledString.length() > 1)
{
    assembledString.erase(0, 1);

    cout << assembledString;

    convertedString = atoi(assembledString);


}

else
{
    cout << "I'm an operator " << assembledString;
}
}
Jason
  • 119
  • 8
  • Could you show a code example of when it is failing? – Daniel Feb 11 '18 at 17:20
  • it says no suitable conversion from string to const char exists – Jason Feb 11 '18 at 17:23
  • Does this really work when you pass a string in quotes? You are using atoi() and not atof(), thus converting it to an integer instead of a double. – John M. Feb 11 '18 at 17:26
  • You should pass `std::string const &assembledString` and use `assembledString.substr(1)` instead of `.erase()` – Killzone Kid Feb 11 '18 at 17:40
  • I made a mistake when posting the code. I did atoi to see if the same result would happen as when I used atof. I did mean to post the version with atof. – Jason Feb 11 '18 at 18:35

1 Answers1

5

You need std::stod1

convertedString = std::stod(assembledString);

Note that you could also use std::atof, passing it assembledString.c_str(). But std::atoi would make little sense here.


1 Besides the fact that atoi is for converting to integer, not double

juanchopanza
  • 223,364
  • 34
  • 402
  • 480