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 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
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
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
template<typename T>
T convertTo(const string& fromString) {
T toT;
istringstream(fromString)>>toT;
return toT;
}
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.
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
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.
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 -
#ifndef Def_STD
-
#define Def_STD
-
#include <iostream>
-
#include <string>
-
#include <cmath>
-
using namespace std;
-
class STD
-
{
-
public:
-
int i,p;bool b;double d;
-
int cti(string s){//this converts a single values string to an integer
-
if (s=="0"){return 0;}else if(s=="1"){return 1;}
-
else if(s=="2"){return 2;}else if(s=="3"){return 3;}
-
else if(s=="4"){return 4;}else if(s=="5"){return 5;}
-
else if(s=="6"){return 6;}else if(s=="7"){return 7;}
-
else if(s=="8"){return 8;}else if(s=="9"){return 9;}
-
return 0;}
-
int sti(string s){//this converts a string to an integer
-
i=0;b=false;
-
if(s.substr(0,1)=="-"){s=s.substr(1,s.length()-1);b=true;}
-
for(int c=0;c<s.length();c++){
-
i+=cti(s.substr(s.length()-c-1,1))*pow(10,c);}
-
if(b){i*=-1;}
-
return i;}
-
double std(string s){//this converts a string to a double
-
d=0;p=-1;
-
for(int c=0;c<s.length();c++){
-
if(s.substr(c,1)=="."){
-
p=s.length()-c-1;
-
if(c==0){s=s.substr(1,s.length()-1);}
-
else if(c==s.length()-1){s=s.substr(0,s.length()-1);}
-
else{s=s.substr(0,c)+s.substr(c+1,s.length()-c-1);}}}
-
d = sti(s);
-
if(p!=-1){d/=pow(10,p);}
-
return d;}
-
STD::STD(){i=0;b=false;d=0;p=-1;}
-
};
-
#endif
-
/*
-
Function 'double std(string)' accepts a string of form '-i[n].i[n]' where i is a substring '0' through '9',
-
and returns the double of the intended value.
-
Both the decimal place and the negative sign are optional.
-
The decimal place can be anywhere in the string, however the dash must be a leading dash.
-
There is no error checking. If there is a chance that a string could be dirty with values other than '-', '.', or
-
'0' through '9', then you must create something to clean it first.
-
Dirty strings may return unintended values of form double, but will not cause any other errors.
-
-
Function 'int sti(int)' accepts a string of form '-i[n]' where i is a substring '0' through '9',
-
and returns the integer of the intended value.
-
The negative sign is optional. If present, it must be in the form of a leading dash.
-
There is no error checking. If there is a chance that a string could be dirty with values other than '-', '.', or
-
'0' through '9', then you must create something to clean it first.
-
Dirty strings may return unintended values of form double, but will not cause any other errors.
-
-
Function 'int cti(int)' isn't very useful. It simply bruteforces a single valued string into an integer
-
of value 0 through 9.
-
*/
-
Heres a little tester so you can see what kind of input works and what doesn't. -
#include <iostream>
-
#include <string>
-
#include "STD.h"
-
using namespace std;
-
-
void main(int *argv, int *argc)
-
{
-
string s;
-
double d;
-
STD std;
-
-
while(s != "end")
-
{
-
cin>>s;
-
d = std.std(s);
-
cout<<"data: "<<d<<endl;
-
}
-
}
-
I hope this helps somebody.
Nevermind im an idiot!
//start
#include <string>
double doubleVar;
string stringVar
doubleVar = atof(stringVar.c_str());
//done!
This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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...
|
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...
|
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...
|
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...
|
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...
| |
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,...
|
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...
|
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...
|
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...
|
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...
|
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...
| |
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,...
|
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...
|
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...
|
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...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |