Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string into a double, and a int. How to?

Tags:

c++

I'm having trouble converting a string into a double. My string has been declared using the "string" function, so my string is:

string marks = "";

Now to convert it to a double I found somewhere on the internet to use word.c_str(), and so I did. I called it and used it like this:

doubleMARK = strtod( marks.c_str() );

This is similar to the example I found on the web:

n1=strtod( t1.c_str() );

Apparently, that's how it's done. But of course, it doesn't work. I need another parameter. A pointer I believe? But I'm lost at this point as to what I'm suppose to do. Does it need a place to store the value or something? or what?

I also need to convert this string into a integer which I have not begun researching as to how to do, but once I find out and if I have errors, I will edit this out and post them here.

like image 913
Robolisk Avatar asked Jan 23 '12 03:01

Robolisk


1 Answers

Was there a reason you're not using std::stod and std::stoi? They are at least 9 levels more powerful than flimsy strtod.

Example

#include <iostream>
#include <string>

int main() {
  using namespace std;
  string s = "-1";
  double d = stod(s);
  int i = stoi(s);
  cout << s << " " << d << " " << i << endl;
}

Output

-1 -1 -1

If you must use strtod, then just pass NULL as the second parameter. According to cplusplus.com:

If [the second parameter] is not a null pointer, the function also sets the value pointed by endptr to point to the first character after the number.

And it's not required to be non-NULL.

like image 135
Seth Carnegie Avatar answered Sep 23 '22 19:09

Seth Carnegie