Convert double to string using boost::lexical_cast in C++? - c++

I' d like to use lexical_cast to convert a float to a string. Usually it works fine, but I have some problems with numbers without decimal. How can I fix number of decimal shown in the string?
Example:
double n=5;
string number;
number = boost::lexical_cast<string>(n);
Result number is 5, I need number 5.00.

From the documentation for boost lexical_cast:
For more involved conversions, such as where precision or formatting need tighter control than is offered by the default behavior of lexical_cast, the conventional stringstream approach is recommended. Where the conversions are numeric to numeric, numeric_cast may offer more reasonable behavior than lexical_cast.
Example:
#include <sstream>
#include <iomanip>
int main() {
std::ostringstream ss;
double x = 5;
ss << std::fixed << std::setprecision(2);
ss << x;
std::string s = ss.str();
return 0;
}

Have a look at boost::format library. It merges the usability of printf with type safety of streams. For speed, I do not know, but I doubt it really matters nowadays.
#include <boost/format.hpp>
#include <iostream>
int main()
{
double x = 5.0;
std::cout << boost::str(boost::format("%.2f") % x) << '\n';
}

If you need complex formatting, use std::ostringstream instead. boost::lexical_cast is meant for "simple formatting".
std::string
get_formatted_value(double d) {
std::ostringstream oss;
oss.setprecision(3);
oss.setf(std::ostringstream::showpoint);
oss << d;
return oss.str();
}

you can also use sprintf, which is faster then ostringstream
#include <cstdio>
#include <string>
using namespace std;
int main()
{
double n = 5.0;
char str_tmp[50];
sprintf(str_tmp, "%.2f", n);
string number(str_tmp);
}

Related

How can I enter (i+1) as a string? [duplicate]

What is the easiest way to convert from int to equivalent string in C++? I am aware of two methods. Is there an easier way?
(1)
int a = 10;
char *intStr = itoa(a);
string str = string(intStr);
(2)
int a = 10;
stringstream ss;
ss << a;
string str = ss.str();
C++11 introduces std::stoi (and variants for each numeric type) and std::to_string, the counterparts of the C atoi and itoa but expressed in term of std::string.
#include <string>
std::string s = std::to_string(42);
is therefore the shortest way I can think of. You can even omit naming the type, using the auto keyword:
auto s = std::to_string(42);
Note: see [string.conversions] (21.5 in n3242)
C++20: std::format would be the idiomatic way now.
C++17:
Picking up a discussion with #v.oddou a couple of years later, C++17 has delivered a way to do the originally macro-based type-agnostic solution (preserved below) without going through macro ugliness.
// variadic template
template < typename... Args >
std::string sstr( Args &&... args )
{
std::ostringstream sstr;
// fold expression
( sstr << std::dec << ... << args );
return sstr.str();
}
Usage:
int i = 42;
std::string s = sstr( "i is: ", i );
puts( sstr( i ).c_str() );
Foo x( 42 );
throw std::runtime_error( sstr( "Foo is '", x, "', i is ", i ) );
C++98:
Since "converting ... to string" is a recurring problem, I always define the SSTR() macro in a central header of my C++ sources:
#include <sstream>
#define SSTR( x ) static_cast< std::ostringstream & >( \
( std::ostringstream() << std::dec << x ) ).str()
Usage is as easy as could be:
int i = 42;
std::string s = SSTR( "i is: " << i );
puts( SSTR( i ).c_str() );
Foo x( 42 );
throw std::runtime_error( SSTR( "Foo is '" << x << "', i is " << i ) );
The above is C++98 compatible (if you cannot use C++11 std::to_string), and does not need any third-party includes (if you cannot use Boost lexical_cast<>); both these other solutions have a better performance though.
Current C++
Starting with C++11, there's a std::to_string function overloaded for integer types, so you can use code like:
int a = 20;
std::string s = std::to_string(a);
// or: auto s = std::to_string(a);
The standard defines these as being equivalent to doing the conversion with sprintf (using the conversion specifier that matches the supplied type of object, such as %d for int), into a buffer of sufficient size, then creating an std::string of the contents of that buffer.
Old C++
For older (pre-C++11) compilers, probably the most common easy way wraps essentially your second choice into a template that's usually named lexical_cast, such as the one in Boost, so your code looks like this:
int a = 10;
string s = lexical_cast<string>(a);
One nicety of this is that it supports other casts as well (e.g., in the opposite direction works just as well).
Also note that although Boost lexical_cast started out as just writing to a stringstream, then extracting back out of the stream, it now has a couple of additions. First of all, specializations for quite a few types have been added, so for many common types, it's substantially faster than using a stringstream. Second, it now checks the result, so (for example) if you convert from a string to an int, it can throw an exception if the string contains something that couldn't be converted to an int (e.g., 1234 would succeed, but 123abc would throw).
I usually use the following method:
#include <sstream>
template <typename T>
std::string NumberToString ( T Number )
{
std::ostringstream ss;
ss << Number;
return ss.str();
}
It is described in details here.
You can use std::to_string available in C++11 as suggested by Matthieu M.:
std::string s = std::to_string(42);
Or, if performance is critical (for example, if you do lots of conversions), you can use fmt::format_int from the {fmt} library to convert an integer to std::string:
std::string s = fmt::format_int(42).str();
Or a C string:
fmt::format_int f(42);
const char* s = f.c_str();
The latter doesn't do any dynamic memory allocations and is more than 70% faster than libstdc++ implementation of std::to_string on Boost Karma benchmarks. See Converting a hundred million integers to strings per second for more details.
Disclaimer: I'm the author of the {fmt} library.
If you have Boost installed (which you should):
#include <boost/lexical_cast.hpp>
int num = 4;
std::string str = boost::lexical_cast<std::string>(num);
It would be easier using stringstreams:
#include <sstream>
int x = 42; // The integer
string str; // The string
ostringstream temp; // 'temp' as in temporary
temp << x;
str = temp.str(); // str is 'temp' as string
Or make a function:
#include <sstream>
string IntToString(int a)
{
ostringstream temp;
temp << a;
return temp.str();
}
Not that I know of, in pure C++. But a little modification of what you mentioned
string s = string(itoa(a));
should work, and it's pretty short.
sprintf() is pretty good for format conversion. You can then assign the resulting C string to the C++ string as you did in 1.
Using stringstream for number conversion is dangerous!
See std::ostream::operator<< where it tells that operator<< inserts formatted output.
Depending on your current locale an integer greater than three digits, could convert to a string of four digits, adding an extra thousands separator.
E.g., int = 1000 could be converted to a string 1.001. This could make comparison operations not work at all.
So I would strongly recommend using the std::to_string way. It is easier and does what you expect.
From std::to_string:
C++17 provides std::to_chars as a higher-performance locale-independent alternative.
First include:
#include <string>
#include <sstream>
Second add the method:
template <typename T>
string NumberToString(T pNumber)
{
ostringstream oOStrStream;
oOStrStream << pNumber;
return oOStrStream.str();
}
Use the method like this:
NumberToString(69);
or
int x = 69;
string vStr = NumberToString(x) + " Hello word!."
In C++11 we can use the "to_string()" function to convert an int into a string:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int x = 1612;
string s = to_string(x);
cout << s<< endl;
return 0;
}
C++17 provides std::to_chars as a higher-performance locale-independent alternative.
If you need fast conversion of an integer with a fixed number of digits to char* left-padded with '0', this is the example for little-endian architectures (all x86, x86_64 and others):
If you are converting a two-digit number:
int32_t s = 0x3030 | (n/10) | (n%10) << 8;
If you are converting a three-digit number:
int32_t s = 0x303030 | (n/100) | (n/10%10) << 8 | (n%10) << 16;
If you are converting a four-digit number:
int64_t s = 0x30303030 | (n/1000) | (n/100%10)<<8 | (n/10%10)<<16 | (n%10)<<24;
And so on up to seven-digit numbers. In this example n is a given integer. After conversion it's string representation can be accessed as (char*)&s:
std::cout << (char*)&s << std::endl;
Note: If you need it on big-endian byte order, though I did not tested it, but here is an example: for three-digit number it is int32_t s = 0x00303030 | (n/100)<< 24 | (n/10%10)<<16 | (n%10)<<8; for four-digit numbers (64 bit arch): int64_t s = 0x0000000030303030 | (n/1000)<<56 | (n/100%10)<<48 | (n/10%10)<<40 | (n%10)<<32; I think it should work.
It's rather easy to add some syntactical sugar that allows one to compose strings on the fly in a stream-like way
#include <string>
#include <sstream>
struct strmake {
std::stringstream s;
template <typename T> strmake& operator << (const T& x) {
s << x; return *this;
}
operator std::string() {return s.str();}
};
Now you may append whatever you want (provided that an operator << (std::ostream& ..) is defined for it) to strmake() and use it in place of an std::string.
Example:
#include <iostream>
int main() {
std::string x =
strmake() << "Current time is " << 5+5 << ":" << 5*5 << " GST";
std::cout << x << std::endl;
}
Use:
#define convertToString(x) #x
int main()
{
convertToString(42); // Returns const char* equivalent of 42
}
int i = 255;
std::string s = std::to_string(i);
In C++, to_string() will create a string object of the integer value by representing the value as a sequence of characters.
I use:
int myint = 0;
long double myLD = 0.0;
string myint_str = static_cast<ostringstream*>(&(ostringstream() << myint))->str();
string myLD_str = static_cast<ostringstream*>(&(ostringstream() << myLD))->str();
It works on my Windows and Linux g++ compilers.
Here's another easy way to do
char str[100];
sprintf(str, "%d", 101);
string s = str;
sprintf is a well-known one to insert any data into a string of the required format.
You can convert a char * array to a string as shown in the third line.
If you're using MFC, you can use CString:
int a = 10;
CString strA;
strA.Format("%d", a);
C++11 introduced std::to_string() for numeric types:
int n = 123; // Input, signed/unsigned short/int/long/long long/float/double
std::string str = std::to_string(n); // Output, std::string
Use:
#include<iostream>
#include<string>
std::string intToString(int num);
int main()
{
int integer = 4782151;
std::string integerAsStr = intToString(integer);
std::cout << "integer = " << integer << std::endl;
std::cout << "integerAsStr = " << integerAsStr << std::endl;
return 0;
}
std::string intToString(int num)
{
std::string numAsStr;
bool isNegative = num < 0;
if(isNegative) num*=-1;
do
{
char toInsert = (num % 10) + 48;
numAsStr.insert(0, 1, toInsert);
num /= 10;
}while (num);
return isNegative? numAsStr.insert(0, 1, '-') : numAsStr;
}
All you have to do is use String when defining your variable (String intStr). Whenever you need that variable, call whateverFunction(intStr.toInt())
Using the plain standard stdio header, you can cast the integer over sprintf into a buffer, like so:
#include <stdio.h>
int main()
{
int x = 23;
char y[2]; // The output buffer
sprintf(y, "%d", x);
printf("%s", y)
}
Remember to take care of your buffer size according to your needs (the string output size).
string number_to_string(int x) {
if (!x)
return "0";
string s, s2;
while(x) {
s.push_back(x%10 + '0');
x /= 10;
}
reverse(s.begin(), s.end());
return s;
}
This worked for me -
My code:
#include <iostream>
using namespace std;
int main()
{
int n = 32;
string s = to_string(n);
cout << "string: " + s << endl;
return 0;
}
I think using stringstream is pretty easy:
string toString(int n)
{
stringstream ss(n);
ss << n;
return ss.str();
}
int main()
{
int n;
cin >> n;
cout << toString(n) << endl;
return 0;
}
char * bufSecs = new char[32];
char * bufMs = new char[32];
sprintf(bufSecs, "%d", timeStart.elapsed()/1000);
sprintf(bufMs, "%d", timeStart.elapsed()%1000);
namespace std
{
inline string to_string(int _Val)
{ // Convert long long to string
char _Buf[2 * _MAX_INT_DIG];
snprintf(_Buf, "%d", _Val);
return (string(_Buf));
}
}
You can now use to_string(5).
You use a counter type of algorithm to convert to a string. I got this technique from programming Commodore 64 computers. It is also good for game programming.
You take the integer and take each digit that is weighted by powers of 10. So assume the integer is 950.
If the integer equals or is greater than 100,000 then subtract 100,000 and increase the counter in the string at ["000000"];
keep doing it until no more numbers in position 100,000.
Drop another power of ten.
If the integer equals or is greater than 10,000 then subtract 10,000 and increase the counter in the string at ["000000"] + 1 position;
keep doing it until no more numbers in position 10,000.
Drop another power of ten
Repeat the pattern
I know 950 is too small to use as an example, but I hope you get the idea.

Best way to cast numbers into strings in C++? [duplicate]

This question already has answers here:
Easiest way to convert int to string in C++
(30 answers)
Closed 9 years ago.
Coming from a C# background, In C# I could write this:
int int1 = 0;
double double1 = 0;
float float1 = 0;
string str = "words" + int1 + double1 + float1;
..and the casting to strings is implicit. In C++ I understand the casting has to be explicit, and I was wondering how the problem was usually tackled by a C++ programmer?
There's plenty of info on the net already I know, but there seems to quite a number of ways to do it and I was wondering if there wasn't a standard practice in place?
If you were to write that above code in C++, how would you do it?
Strings in C++ are just containers of bytes, really, so we must rely on additional functionality to do this for us.
In the olden days of C++03, we'd typically use I/O streams' built-in lexical conversion facility (via formatted input):
int int1 = 0;
double double1 = 0;
float float1 = 0;
std::stringstream ss;
ss << "words" << int1 << double1 << float1;
std::string str = ss.str();
You can use various I/O manipulators to fine-tune the result, much as you would in a sprintf format string (which is still valid, and still seen in some C++ code).
There are other ways, that convert each argument on its own then rely on concatenating all the resulting strings. boost::lexical_cast provides this, as does C++11's to_string:
int int1 = 0;
double double1 = 0;
float float1 = 0;
std::string str = "words"
+ std::to_string(int1)
+ std::to_string(double1)
+ std::to_string(float1);
This latter approach doesn't give you any control over how the data is represented, though (demo).
std::stringstream
std::to_string
If you can use Boost.LexicalCast (available for C++98 even), then it's pretty straightforward:
#include <boost/lexical_cast.hpp>
#include <iostream>
int main( int argc, char * argv[] )
{
int int1 = 0;
double double1 = 0;
float float1 = 0;
std::string str = "words"
+ boost::lexical_cast<std::string>(int1)
+ boost::lexical_cast<std::string>(double1)
+ boost::lexical_cast<std::string>(float1)
;
std::cout << str;
}
Live Example.
Note that as of C++11, you can also use std::to_string as mentioned by #LigthnessRacesinOrbit.
Being a C developer, I would use the C string functions, as they are perfectly valid in C++, and let you be VERY explicit with respect to the formatting of numbers (ie: integers, floating point, etc).
http://www.cplusplus.com/reference/cstdio/printf/
In the case of this, sprintf() or snprintf() is what you are looking for. The formats specifiers make it very obvious in the source code itself what your intent was as well.
The best way to cast numbers into std::string in C++ is to use what is already available.
The library sstream provide a stream implementation for std::string.
It is like using a stream ( cout, cin ) for example
Its easy to use :
http://www.cplusplus.com/reference/sstream/stringstream/?kw=stringstream
#include <sstream>
using std::stringstream;
#include <string>
using std::string;
#include <iostream>
using std::cout;
using std::endl;
int main(){
stringstream ss;
string str;
int i = 10;
ss << i;
ss >> str;
cout << str << endl;
}

String as a parameter (C++)

Is this example code valid?
std::string x ="There are";
int butterflies = 5;
//the following function expects a string passed as a parameter
number(x + butterflies + "butterflies");
The main question here is whether I could just pass my integer as part of the string using the + operator. But if there are any other errors there please let me know :)
C++ doesn't do automatic conversion to strings like that. You need to create a stringstream or use something like boost lexical cast.
You can use stringstream for this purpose like that:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
stringstream st;
string str;
st << 1 << " " << 2 << " " << "And this is string" << endl;
str = st.str();
cout << str;
return 0;
}
A safe way to convert your integers to strings would be an excerpt as follows:
#include <string>
#include <sstream>
std::string intToString(int x)
{
std::string ret;
std::stringstream ss;
ss << x;
ss >> ret;
return ret;
}
Your current example will not work for reasons mentioned above.
No, it wouldn't work. C++ it no a typeless language. So it can't automatically cast integer to string. Use something like strtol, stringstream, etc.
More C than C++, but sprintf (which is like printf, but puts the result in a string) would be useful here.

Easiest way to convert int to string in C++

What is the easiest way to convert from int to equivalent string in C++? I am aware of two methods. Is there an easier way?
(1)
int a = 10;
char *intStr = itoa(a);
string str = string(intStr);
(2)
int a = 10;
stringstream ss;
ss << a;
string str = ss.str();
C++11 introduces std::stoi (and variants for each numeric type) and std::to_string, the counterparts of the C atoi and itoa but expressed in term of std::string.
#include <string>
std::string s = std::to_string(42);
is therefore the shortest way I can think of. You can even omit naming the type, using the auto keyword:
auto s = std::to_string(42);
Note: see [string.conversions] (21.5 in n3242)
C++20: std::format would be the idiomatic way now.
C++17:
Picking up a discussion with #v.oddou a couple of years later, C++17 has delivered a way to do the originally macro-based type-agnostic solution (preserved below) without going through macro ugliness.
// variadic template
template < typename... Args >
std::string sstr( Args &&... args )
{
std::ostringstream sstr;
// fold expression
( sstr << std::dec << ... << args );
return sstr.str();
}
Usage:
int i = 42;
std::string s = sstr( "i is: ", i );
puts( sstr( i ).c_str() );
Foo x( 42 );
throw std::runtime_error( sstr( "Foo is '", x, "', i is ", i ) );
C++98:
Since "converting ... to string" is a recurring problem, I always define the SSTR() macro in a central header of my C++ sources:
#include <sstream>
#define SSTR( x ) static_cast< std::ostringstream & >( \
( std::ostringstream() << std::dec << x ) ).str()
Usage is as easy as could be:
int i = 42;
std::string s = SSTR( "i is: " << i );
puts( SSTR( i ).c_str() );
Foo x( 42 );
throw std::runtime_error( SSTR( "Foo is '" << x << "', i is " << i ) );
The above is C++98 compatible (if you cannot use C++11 std::to_string), and does not need any third-party includes (if you cannot use Boost lexical_cast<>); both these other solutions have a better performance though.
Current C++
Starting with C++11, there's a std::to_string function overloaded for integer types, so you can use code like:
int a = 20;
std::string s = std::to_string(a);
// or: auto s = std::to_string(a);
The standard defines these as being equivalent to doing the conversion with sprintf (using the conversion specifier that matches the supplied type of object, such as %d for int), into a buffer of sufficient size, then creating an std::string of the contents of that buffer.
Old C++
For older (pre-C++11) compilers, probably the most common easy way wraps essentially your second choice into a template that's usually named lexical_cast, such as the one in Boost, so your code looks like this:
int a = 10;
string s = lexical_cast<string>(a);
One nicety of this is that it supports other casts as well (e.g., in the opposite direction works just as well).
Also note that although Boost lexical_cast started out as just writing to a stringstream, then extracting back out of the stream, it now has a couple of additions. First of all, specializations for quite a few types have been added, so for many common types, it's substantially faster than using a stringstream. Second, it now checks the result, so (for example) if you convert from a string to an int, it can throw an exception if the string contains something that couldn't be converted to an int (e.g., 1234 would succeed, but 123abc would throw).
I usually use the following method:
#include <sstream>
template <typename T>
std::string NumberToString ( T Number )
{
std::ostringstream ss;
ss << Number;
return ss.str();
}
It is described in details here.
You can use std::to_string available in C++11 as suggested by Matthieu M.:
std::string s = std::to_string(42);
Or, if performance is critical (for example, if you do lots of conversions), you can use fmt::format_int from the {fmt} library to convert an integer to std::string:
std::string s = fmt::format_int(42).str();
Or a C string:
fmt::format_int f(42);
const char* s = f.c_str();
The latter doesn't do any dynamic memory allocations and is more than 70% faster than libstdc++ implementation of std::to_string on Boost Karma benchmarks. See Converting a hundred million integers to strings per second for more details.
Disclaimer: I'm the author of the {fmt} library.
If you have Boost installed (which you should):
#include <boost/lexical_cast.hpp>
int num = 4;
std::string str = boost::lexical_cast<std::string>(num);
It would be easier using stringstreams:
#include <sstream>
int x = 42; // The integer
string str; // The string
ostringstream temp; // 'temp' as in temporary
temp << x;
str = temp.str(); // str is 'temp' as string
Or make a function:
#include <sstream>
string IntToString(int a)
{
ostringstream temp;
temp << a;
return temp.str();
}
Not that I know of, in pure C++. But a little modification of what you mentioned
string s = string(itoa(a));
should work, and it's pretty short.
sprintf() is pretty good for format conversion. You can then assign the resulting C string to the C++ string as you did in 1.
Using stringstream for number conversion is dangerous!
See std::ostream::operator<< where it tells that operator<< inserts formatted output.
Depending on your current locale an integer greater than three digits, could convert to a string of four digits, adding an extra thousands separator.
E.g., int = 1000 could be converted to a string 1.001. This could make comparison operations not work at all.
So I would strongly recommend using the std::to_string way. It is easier and does what you expect.
From std::to_string:
C++17 provides std::to_chars as a higher-performance locale-independent alternative.
First include:
#include <string>
#include <sstream>
Second add the method:
template <typename T>
string NumberToString(T pNumber)
{
ostringstream oOStrStream;
oOStrStream << pNumber;
return oOStrStream.str();
}
Use the method like this:
NumberToString(69);
or
int x = 69;
string vStr = NumberToString(x) + " Hello word!."
In C++11 we can use the "to_string()" function to convert an int into a string:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int x = 1612;
string s = to_string(x);
cout << s<< endl;
return 0;
}
C++17 provides std::to_chars as a higher-performance locale-independent alternative.
If you need fast conversion of an integer with a fixed number of digits to char* left-padded with '0', this is the example for little-endian architectures (all x86, x86_64 and others):
If you are converting a two-digit number:
int32_t s = 0x3030 | (n/10) | (n%10) << 8;
If you are converting a three-digit number:
int32_t s = 0x303030 | (n/100) | (n/10%10) << 8 | (n%10) << 16;
If you are converting a four-digit number:
int64_t s = 0x30303030 | (n/1000) | (n/100%10)<<8 | (n/10%10)<<16 | (n%10)<<24;
And so on up to seven-digit numbers. In this example n is a given integer. After conversion it's string representation can be accessed as (char*)&s:
std::cout << (char*)&s << std::endl;
Note: If you need it on big-endian byte order, though I did not tested it, but here is an example: for three-digit number it is int32_t s = 0x00303030 | (n/100)<< 24 | (n/10%10)<<16 | (n%10)<<8; for four-digit numbers (64 bit arch): int64_t s = 0x0000000030303030 | (n/1000)<<56 | (n/100%10)<<48 | (n/10%10)<<40 | (n%10)<<32; I think it should work.
It's rather easy to add some syntactical sugar that allows one to compose strings on the fly in a stream-like way
#include <string>
#include <sstream>
struct strmake {
std::stringstream s;
template <typename T> strmake& operator << (const T& x) {
s << x; return *this;
}
operator std::string() {return s.str();}
};
Now you may append whatever you want (provided that an operator << (std::ostream& ..) is defined for it) to strmake() and use it in place of an std::string.
Example:
#include <iostream>
int main() {
std::string x =
strmake() << "Current time is " << 5+5 << ":" << 5*5 << " GST";
std::cout << x << std::endl;
}
Use:
#define convertToString(x) #x
int main()
{
convertToString(42); // Returns const char* equivalent of 42
}
int i = 255;
std::string s = std::to_string(i);
In C++, to_string() will create a string object of the integer value by representing the value as a sequence of characters.
I use:
int myint = 0;
long double myLD = 0.0;
string myint_str = static_cast<ostringstream*>(&(ostringstream() << myint))->str();
string myLD_str = static_cast<ostringstream*>(&(ostringstream() << myLD))->str();
It works on my Windows and Linux g++ compilers.
Here's another easy way to do
char str[100];
sprintf(str, "%d", 101);
string s = str;
sprintf is a well-known one to insert any data into a string of the required format.
You can convert a char * array to a string as shown in the third line.
If you're using MFC, you can use CString:
int a = 10;
CString strA;
strA.Format("%d", a);
C++11 introduced std::to_string() for numeric types:
int n = 123; // Input, signed/unsigned short/int/long/long long/float/double
std::string str = std::to_string(n); // Output, std::string
Use:
#include<iostream>
#include<string>
std::string intToString(int num);
int main()
{
int integer = 4782151;
std::string integerAsStr = intToString(integer);
std::cout << "integer = " << integer << std::endl;
std::cout << "integerAsStr = " << integerAsStr << std::endl;
return 0;
}
std::string intToString(int num)
{
std::string numAsStr;
bool isNegative = num < 0;
if(isNegative) num*=-1;
do
{
char toInsert = (num % 10) + 48;
numAsStr.insert(0, 1, toInsert);
num /= 10;
}while (num);
return isNegative? numAsStr.insert(0, 1, '-') : numAsStr;
}
All you have to do is use String when defining your variable (String intStr). Whenever you need that variable, call whateverFunction(intStr.toInt())
Using the plain standard stdio header, you can cast the integer over sprintf into a buffer, like so:
#include <stdio.h>
int main()
{
int x = 23;
char y[2]; // The output buffer
sprintf(y, "%d", x);
printf("%s", y)
}
Remember to take care of your buffer size according to your needs (the string output size).
string number_to_string(int x) {
if (!x)
return "0";
string s, s2;
while(x) {
s.push_back(x%10 + '0');
x /= 10;
}
reverse(s.begin(), s.end());
return s;
}
This worked for me -
My code:
#include <iostream>
using namespace std;
int main()
{
int n = 32;
string s = to_string(n);
cout << "string: " + s << endl;
return 0;
}
I think using stringstream is pretty easy:
string toString(int n)
{
stringstream ss(n);
ss << n;
return ss.str();
}
int main()
{
int n;
cin >> n;
cout << toString(n) << endl;
return 0;
}
char * bufSecs = new char[32];
char * bufMs = new char[32];
sprintf(bufSecs, "%d", timeStart.elapsed()/1000);
sprintf(bufMs, "%d", timeStart.elapsed()%1000);
namespace std
{
inline string to_string(int _Val)
{ // Convert long long to string
char _Buf[2 * _MAX_INT_DIG];
snprintf(_Buf, "%d", _Val);
return (string(_Buf));
}
}
You can now use to_string(5).
You use a counter type of algorithm to convert to a string. I got this technique from programming Commodore 64 computers. It is also good for game programming.
You take the integer and take each digit that is weighted by powers of 10. So assume the integer is 950.
If the integer equals or is greater than 100,000 then subtract 100,000 and increase the counter in the string at ["000000"];
keep doing it until no more numbers in position 100,000.
Drop another power of ten.
If the integer equals or is greater than 10,000 then subtract 10,000 and increase the counter in the string at ["000000"] + 1 position;
keep doing it until no more numbers in position 10,000.
Drop another power of ten
Repeat the pattern
I know 950 is too small to use as an example, but I hope you get the idea.

C++ string to double conversion

Usually when I write anything in C++ and I need to convert a char into an int I simply make a new int equal to the char.
I used the code(snippet)
string word;
openfile >> word;
double lol=word;
I receive the error that
Code1.cpp cannot convert `std::string' to `double' in initialization
What does the error mean exactly? The first word is the number 50. Thanks :)
You can convert char to int and viceversa easily because for the machine an int and a char are the same, 8 bits, the only difference comes when they have to be shown in screen, if the number is 65 and is saved as a char, then it will show 'A', if it's saved as a int it will show 65.
With other types things change, because they are stored differently in memory. There's standard function in C that allows you to convert from string to double easily, it's atof. (You need to include stdlib.h)
#include <stdlib.h>
int main()
{
string word;
openfile >> word;
double lol = atof(word.c_str()); /*c_str is needed to convert string to const char*
previously (the function requires it)*/
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << stod(" 99.999 ") << endl;
}
Output: 99.999 (which is double, whitespace was automatically stripped)
Since C++11 converting string to floating-point values (like double) is available with functions:
stof - convert str to a float
stod - convert str to a double
stold - convert str to a long double
As conversion of string to int was also mentioned in the question, there are the following functions in C++11:
stoi - convert str to an int
stol - convert str to a long
stoul - convert str to an unsigned long
stoll - convert str to a long long
stoull - convert str to an unsigned long long
The problem is that C++ is a statically-typed language, meaning that if something is declared as a string, it's a string, and if something is declared as a double, it's a double. Unlike other languages like JavaScript or PHP, there is no way to automatically convert from a string to a numeric value because the conversion might not be well-defined. For example, if you try converting the string "Hi there!" to a double, there's no meaningful conversion. Sure, you could just set the double to 0.0 or NaN, but this would almost certainly be masking the fact that there's a problem in the code.
To fix this, don't buffer the file contents into a string. Instead, just read directly into the double:
double lol;
openfile >> lol;
This reads the value directly as a real number, and if an error occurs will cause the stream's .fail() method to return true. For example:
double lol;
openfile >> lol;
if (openfile.fail()) {
cout << "Couldn't read a double from the file." << endl;
}
If you are reading from a file then you should hear the advice given and just put it into a double.
On the other hand, if you do have, say, a string you could use boost's lexical_cast.
Here is a (very simple) example:
int Foo(std::string anInt)
{
return lexical_cast<int>(anInt);
}
The C++ way of solving conversions (not the classical C) is illustrated with the program below. Note that the intent is to be able to use the same formatting facilities offered by iostream like precision, fill character, padding, hex, and the manipulators, etcetera.
Compile and run this program, then study it. It is simple
#include "iostream"
#include "iomanip"
#include "sstream"
using namespace std;
int main()
{
// Converting the content of a char array or a string to a double variable
double d;
string S;
S = "4.5";
istringstream(S) >> d;
cout << "\nThe value of the double variable d is " << d << endl;
istringstream("9.87654") >> d;
cout << "\nNow the value of the double variable d is " << d << endl;
// Converting a double to string with formatting restrictions
double D=3.771234567;
ostringstream Q;
Q.fill('#');
Q << "<<<" << setprecision(6) << setw(20) << D << ">>>";
S = Q.str(); // formatted converted double is now in string
cout << "\nThe value of the string variable S is " << S << endl;
return 0;
}
Prof. Martinez
Coversion from string to double can be achieved by
using the 'strtod()' function from the library 'stdlib.h'
#include <iostream>
#include <stdlib.h>
int main ()
{
std::string data="20.9";
double value = strtod(data.c_str(), NULL);
std::cout<<value<<'\n';
return 0;
}
#include <string>
#include <cmath>
double _string_to_double(std::string s,unsigned short radix){
double n = 0;
for (unsigned short x = s.size(), y = 0;x>0;)
if(!(s[--x] ^ '.')) // if is equal
n/=pow(10,s.size()-1-x), y+= s.size()-x;
else
n+=( (s[x]-48) * pow(10,s.size()-1-x - y) );
return n;
}
or
//In case you want to convert from different bases.
#include <string>
#include <iostream>
#include <cmath>
double _string_to_double(std::string s,unsigned short radix){
double n = 0;
for (unsigned short x = s.size(), y = 0;x>0;)
if(!(s[--x] ^ '.'))
n/=pow(radix,s.size()-1-x), y+= s.size()-x;
else
n+=( (s[x]- (s[x]<='9' ? '0':'0'+7) ) * pow(radix,s.size()-1-x - y) );
return n;
}
int main(){
std::cout<<_string_to_double("10.A",16)<<std::endl;//Prints 16.625
std::cout<<_string_to_double("1001.1",2)<<std::endl;//Prints 9.5
std::cout<<_string_to_double("123.4",10)<<std::endl;//Prints 123.4
return 0;
}