1

I cannot get the atof() function to work. I only want the user to input values (in the form of decimal numbers) until they enter '|' and it to then break out the loop. I want the values to initially be read in as strings and then converted to doubles because I found in the past when I used this method of input, if you input the number '124' it breaks out of the loop because '124' is the code for the '|' char.

I looked around and found out about the atof() function which apparently converts strings to doubles, however when I try to convert I get the message

"no suitable conversion function from std::string to const char exists".

And I cannot seem to figure why this is.

void distance_vector(){

double total = 0.0;
double mean = 0.0;
string input = " ";
double conversion = 0.0;
vector <double> a;

while (cin >> input && input.compare("|") != 0 ){
conversion = atof(input);
a.push_back(conversion);
}

keep_window_open();
}
NelsonGon
  • 13,015
  • 7
  • 27
  • 57
Shaun1810
  • 317
  • 3
  • 5
  • 15
  • Now that I have answered and received experience, it now makes sense for me to find the duplicate question. http://stackoverflow.com/questions/4754011/c-string-to-double-conversion – djechlin Jul 12 '13 at 16:13

2 Answers2

6

You need

atof(input.c_str());

That would be the "suitable conversion function" in question.

std::string::c_str Documentation:

const char* c_str() const;
Get C string equivalent
Returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.

djechlin
  • 59,258
  • 35
  • 162
  • 290
5

You can also use the strtod function to convert a string to a double:

std::string param;  // gets a value from somewhere
double num = strtod(param.c_str(), NULL);

You can look up the documentation for strtod (e.g. man strtod if you're using Linux / Unix) to see more details about this function.

DMH
  • 3,875
  • 2
  • 26
  • 25