473,499 Members | 1,658 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

String to int and double conversion?

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
9 15048
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
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
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
template<typename T>
T convertTo(const string& fromString) {
T toT;
istringstream(fromString)>>toT;
return toT;
}

Aug 2 '05 #5
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
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
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
Andrew_Hoffman
4 New Member
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
Andrew_Hoffman
4 New Member
Nevermind im an idiot!
//start
#include <string>

double doubleVar;
string stringVar

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

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
4857
by: Der Andere | last post by:
During every iteration in a loop, I need to convert a double value into a char*. Simple type-casting did not work, so I thought of using stringstreams. However, the stream would have to be...
31
6575
by: Bjørn Augestad | last post by:
Below is a program which converts a double to an integer in two different ways, giving me two different values for the int. The basic expression is 1.0 / (1.0 * 365.0) which should be 365, but one...
12
2177
by: ABeck | last post by:
Hello List, I have ar more or less academical question. Can there arise runtime errors in a program, if the include of <string.h> has been forgotten? If all the arguments to the functions of...
8
3251
by: Oenone | last post by:
Is it possible to create an object which can have methods and properties, but which can also be treated as a string? I'm trying to create a wrapper around the IIS Request.Form object which...
20
2140
by: Trond Valen | last post by:
Hi! Stupid atof, it returns 0.0 when it tries to parse something like "fish". So I don't know whether the number was really 0 or a string that couldn't be parsed. Is there a better way to do...
6
7591
by: karthi | last post by:
hi, I need user defined function that converts string to float in c. since the library function atof and strtod occupies large space in my processor memory I can't use it in my code. regards,...
21
4149
by: utab | last post by:
Hi there, Is there a way to convert a double value to a string. I know that there is fcvt() but I think this function is not a part of the standard library. I want sth from the standard if...
14
2895
by: nishit.gupta | last post by:
Is their any single fuction available in C++ that can determine that a string contains a numeric value. The value cabn be in hex, int, float. i.e. "1256" , "123.566" , "0xffff" , It can also...
14
2140
by: Aman JIANG | last post by:
hi i need a fast way to do lots of conversion that between string and numerical value(integer, float, double...), and boost::lexical_cast is useless, because it runs for a long time, (about 60...
2
4618
by: Lior Bobrov | last post by:
Hi ... How to convert a variable of type Double to String , *preserving* the original value of the Double variable , as is , in a short (convenient) way ? For example , if there are two...
0
7009
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7178
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7223
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
7390
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
4919
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4602
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3094
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
665
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
302
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.