By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,120 Members | 1,275 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,120 IT Pros & Developers. It's quick & easy.

String to int and double conversion?

P: n/a
What is the best way to convert from a string to a int and from a
string to double? I have a line that is tokenize and I need to parse to
test the tokens and convert them to their respective values from
string.

Thanks,
N

Aug 1 '05 #1
Share this Question
Share on Google+
9 Replies


P: n/a
atoi and atof in <cstdlib>

el_boricua wrote:
What is the best way to convert from a string to a int and from a
string to double? I have a line that is tokenize and I need to parse to
test the tokens and convert them to their respective values from
string.

Thanks,
N

Aug 1 '05 #2

P: n/a
el_boricua wrote:
What is the best way to convert from a string to a int and from a
string to double? I have a line that is tokenize and I need to parse to
test the tokens and convert them to their respective values from
string.


Look up std::ostringstream and std::istringstream.
Jonathan

Aug 1 '05 #3

P: n/a
On Mon, 01 Aug 2005 12:19:09 -0700, Gang Ji <ga**@ee.washington.edu>
wrote in comp.lang.c++:

1. Don't top post. Material in your reply should come AFTER quoted
material from the original post you refer to.
atoi and atof in <cstdlib>
2. Don't post what you don't know. The ato* functions from
<stdlib.h> or <cstdlib> should NEVER be used in a C++ program, or a C
one for that matter. They produce undefined behavior if the converted
value is too large for the return type.

The strto* functions were added to C when it was standardized more
than 15 years ago, specifically to replace the old, unsafe functions,
because the new ones have fully defined behavior with any input other
than a null pointer.
el_boricua wrote:
What is the best way to convert from a string to a int and from a
string to double? I have a line that is tokenize and I need to parse to
test the tokens and convert them to their respective values from
string.

Thanks,
N


And of course C++ has other methods of its own, as others have pointer
out.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Aug 2 '05 #4

P: n/a
template<typename T>
T convertTo(const string& fromString) {
T toT;
istringstream(fromString)>>toT;
return toT;
}

Aug 2 '05 #5

P: n/a
elviin wrote:
template<typename T>
T convertTo(const string& fromString) {
T toT;
istringstream(fromString)>>toT;
return toT;
}


This looks neat, but how would you do error checking?

int a = convertTo("42"); // OK
int b = convertTo("1x"); // Error
short c = convertTo("100000"); // Error
unsigned d = convertTo("-1"); // Error
int e = convertTo("1.2"); // Error
double f = convertTo("1x"); // Error

Thanks.
Aug 2 '05 #6

P: n/a
Jacob wrote:
elviin wrote:
template<typename T>
T convertTo(const string& fromString) {
T toT;
istringstream(fromString)>>toT;
return toT;
}

This looks neat, but how would you do error checking?

int a = convertTo("42"); // OK
int b = convertTo("1x"); // Error
short c = convertTo("100000"); // Error
unsigned d = convertTo("-1"); // Error
int e = convertTo("1.2"); // Error
double f = convertTo("1x"); // Error

Thanks.

Write "convertTo" as follow:

template<typename T>
T convertTo(const string& fromString, T& toT)
{
istringstream(str) >> toT;
return toT;
}

and use it like this:

int a;
convertTo("42", a);

try it~~
--
Best Regards

Xie Yubo
Email: xi*****@gmail.com Website: http://xieyubo.cn/
Harbin Institute of Technology
Phone: 86-451-86416614 Fax: 86-451-86413309
Aug 2 '05 #7

P: n/a
template<typename T>
inline T convertToFrom( const std::string& fromString ) {
T toT;
std::istringstream tmStream(fromString);
char c;
if( !(tmStream >> toT) || tmStream.get(c))
throw std::out_of_range( "convertToStdNumericType is
std::out_of_range." );
return toT;
}

But I think that >> operator IMHO should return a position of any
left-over character instead of bool value. That would provide more
information.

Aug 2 '05 #8

P: 4
I've had an aweful time trying to figure out how to convert an std::string to a double.
After hours with no success, I decided to make my one little dirty converter.
There is no error checking in it. Read the bottom to learn how the input must be formatted.

STD.h
Expand|Select|Wrap|Line Numbers
  1. #ifndef Def_STD
  2. #define Def_STD
  3. #include <iostream>
  4. #include <string>
  5. #include <cmath>
  6. using namespace std;
  7. class STD
  8. {
  9. public:
  10.     int i,p;bool b;double d;
  11.     int cti(string s){//this converts a single values string to an integer
  12.         if     (s=="0"){return 0;}else if(s=="1"){return 1;}
  13.         else if(s=="2"){return 2;}else if(s=="3"){return 3;}
  14.         else if(s=="4"){return 4;}else if(s=="5"){return 5;}
  15.         else if(s=="6"){return 6;}else if(s=="7"){return 7;}
  16.         else if(s=="8"){return 8;}else if(s=="9"){return 9;}
  17.         return 0;}
  18.     int sti(string s){//this converts a string to an integer
  19.         i=0;b=false;
  20.         if(s.substr(0,1)=="-"){s=s.substr(1,s.length()-1);b=true;}
  21.         for(int c=0;c<s.length();c++){
  22.             i+=cti(s.substr(s.length()-c-1,1))*pow(10,c);}
  23.         if(b){i*=-1;}
  24.         return i;}
  25.     double std(string s){//this converts a string to a double
  26.         d=0;p=-1;
  27.         for(int c=0;c<s.length();c++){
  28.             if(s.substr(c,1)=="."){
  29.                 p=s.length()-c-1;
  30.                 if(c==0){s=s.substr(1,s.length()-1);}
  31.                 else if(c==s.length()-1){s=s.substr(0,s.length()-1);}
  32.                 else{s=s.substr(0,c)+s.substr(c+1,s.length()-c-1);}}}
  33.         d = sti(s);
  34.         if(p!=-1){d/=pow(10,p);}
  35.         return d;}
  36.     STD::STD(){i=0;b=false;d=0;p=-1;}
  37. };
  38. #endif
  39. /*
  40. Function 'double std(string)' accepts a string of form '-i[n].i[n]' where i is a substring '0' through '9',
  41. and returns the double of the intended value.
  42. Both the decimal place and the negative sign are optional.
  43. The decimal place can be anywhere in the string, however the dash must be a leading dash.
  44. There is no error checking. If there is a chance that a string could be dirty with values other than '-', '.', or
  45. '0' through '9', then you must create something to clean it first.
  46. Dirty strings may return unintended values of form double, but will not cause any other errors.
  47.  
  48. Function 'int sti(int)' accepts a string of form '-i[n]' where i is a substring '0' through '9',
  49. and returns the integer of the intended value.
  50. The negative sign is optional. If present, it must be in the form of a leading dash.
  51. There is no error checking. If there is a chance that a string could be dirty with values other than '-', '.', or
  52. '0' through '9', then you must create something to clean it first.
  53. Dirty strings may return unintended values of form double, but will not cause any other errors.
  54.  
  55. Function 'int cti(int)' isn't very useful. It simply bruteforces a single valued string into an integer
  56. of value 0 through 9.
  57. */
  58.  
Heres a little tester so you can see what kind of input works and what doesn't.
Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <string>
  3. #include "STD.h"
  4. using namespace std;
  5.  
  6. void main(int *argv, int *argc)
  7. {
  8. string s;
  9. double d;
  10. STD std;
  11.  
  12. while(s != "end")
  13. {
  14.          cin>>s;
  15.          d = std.std(s);
  16.          cout<<"data: "<<d<<endl;
  17. }
  18. }
  19.  
I hope this helps somebody.
Aug 31 '05 #9

P: 4
Nevermind im an idiot!
//start
#include <string>

double doubleVar;
string stringVar

doubleVar = atof(stringVar.c_str());
//done!
Sep 9 '05 #10

This discussion thread is closed

Replies have been disabled for this discussion.