How do I convert a long to a string in C++? - c++

How do I convert a long to a string in C++?

In C++11, there are actually std::to_string and std::to_wstring functions in <string>.
string to_string(int val);
string to_string(long val);
string to_string(long long val);
string to_string(unsigned val);
string to_string(unsigned long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string (long double val);

You could use stringstream.
#include <sstream>
// ...
std::string number;
std::stringstream strstream;
strstream << 1L;
strstream >> number;
There is usually some proprietary C functions in the standard library for your compiler that does it too. I prefer the more "portable" variants though.
The C way to do it would be with sprintf, but that is not very secure. In some libraries there is new versions like sprintf_s which protects against buffer overruns.

Well if you are fan of copy-paste, here it is:
#include <sstream>
template <class T>
inline std::string to_string (const T& t)
{
std::stringstream ss;
ss << t;
return ss.str();
}

boost::lexical_cast<std::string>(my_long)
more here http://www.boost.org/doc/libs/1_39_0/libs/conversion/lexical_cast.htm

You can use std::to_string in C++11
long val = 12345;
std::string my_val = std::to_string(val);

int main()
{
long mylong = 123456789;
string mystring;
stringstream mystream;
mystream << mylong;
mystring = mystream.str();
cout << mystring << "\n";
return 0;
}

I don't know what kind of homework this is, but most probably the teacher doesn't want an answer where you just call a "magical" existing function (even though that's the recommended way to do it), but he wants to see if you can implement this by your own.
Back in the days, my teacher used to say something like "I want to see if you can program by yourself, not if you can find it in the system." Well, how wrong he was ;) ..
Anyway, if your teacher is the same, here is the hard way to do it..
std::string LongToString(long value)
{
std::string output;
std::string sign;
if(value < 0)
{
sign + "-";
value = -value;
}
while(output.empty() || (value > 0))
{
output.push_front(value % 10 + '0')
value /= 10;
}
return sign + output;
}
You could argue that using std::string is not "the hard way", but I guess what counts in the actual agorithm.

There are several ways. Read The String Formatters of Manor Farm for an in-depth comparison.

#include <sstream>
....
std::stringstream ss;
ss << a_long_int; // or any other type
std::string result=ss.str(); // use .str() to get a string back

Check out std::stringstream.

One of the things not covered by anybody so far, to help you think about the problem further, is what format should a long take when it is cast to a string.
Just have a look at a spreedsheet program (like Calc/Excel). Do you want it rounded to the nearest million, with brackets if it's negative, always to show the sign.... Is the number realy a representation of something else, should you show it in Oractal or Hex instead?
The answers so far have given you some default output, but perhaps not the right ones.

The way I typically do it is with sprintf. So for a long you could do the following assuming that you are on a 32 bit architecture:
char buf[5] = {0}; // one extra byte for null
sprintf(buf, "%l", var_for_long);

Related

How to convert a double variable into a char array?

I'm working on a project for school, and we just found out that outtextxy() (a function from graphics.h, which we must use) requires as the text parameter a char array.
Here is its declaration: void outtextxy (int x, int y, char *textstring)
The issue is that we need to print out a number of type double, including the decimal point. I have previously tried making it work using knowledge from other similar questions, but none has worked.
Here are is my latest attempt, which resulted in a Segmentation Fault:
char *DoubleToString(long double x)
{
char s[256]="\000";
std::ostringstream strs;
strs << x;
string ss = strs.str();
for(int i=0; i < ss.length(); i++)
s[i] = ss[i];
return s;
}
NOTE: I am still somewhat new to programming and I don't exactly know what ostringstream and the bitshift-looking operation are doing, but I tried to copy-paste that part in hopes of it working.
... requires as the text parameter a char array.
Ok, then use a std::string:
std::string DoubleToString(long double x)
{
std::ostringstream strs;
strs << x;
return strs.str();
}
If you need the underlying character array use the strings data() method. It does return a pointer to the first element of the strings character array. For example:
std::string s = DoubleToString(3.141);
function_that_needs_pointer_to_char( s.data() );
Note that before C++17 data returned a const char* (and since C++11 the character array is null-terminated, as one would expect ;).
I know it is undefined behaviour, but it works. And I only need to pass the returned char* to outtextxy(), and not manipulate it later on, since I have the double variable stored in an object.
char *DoubleToString(long double x)
{
char s[256]="\000";
std::ostringstream strs;
strs << x;
string sd = strs.str();
strcpy(s, sd.data());
return s;
}

Automatically Concatenate Strings and Int C++

In Lua (apologise, I like working with it the best), the conversion between int and string is done automatically, so
"hi"..2
would result as
"hi2"
In C++ (cause I can't seem to get the default C++11 stoi() and to_string() methods to work) I defined these for myself:
int stoi(string str) {
char* ptr;
strtol(str.c_str(), &ptr, 10);
}
string to_string(int i) {
char* buf;
sprintf(buf, "%d", i);
return buf;
}
which are basically how the default ones are defined anyways.
Then I did this:
string operator+ (string& stuff, int why) {
stuff.append(to_string(why));
}
I tried it on the following code:
void print(string str) {
cout << str << endl;
}
int main() {
cout << stoi("1") + 2 << endl;
print("die" + 1);
return 0;
}
And it outputs
3
ie
Why is this so, and how can I fix it?
EDIT:
Here's what the code looks like now:
using namespace std;
string to_string(int i) {
char* buf;
sprintf(buf, "%d", i);
return buf;
}
string operator+ (string stuff, int why) {
stuff.append(to_string(why));
return stuff;
}
int main() {
cout << string("die") + 2 << endl;
return 0;
}
And it just keeps giving me stackdumps.
Replace print("die" + 1); with cout << std::string("die") + 1;
print() doesn't know what to do with strings. Use std::cout. "die" is a char*, +1 will increment the pointer.
std::string to_string(int i) {
char buf[(sizeof(int)*CHAR_BIT+2)/3+3];
sprintf(buf, "%d", i);
return buf;
}
You need to make an actual buffer to print to. The math is a quick over-estimate of big the largest decimal int is in characters; 3 bits can fit in 1 decimal character, plus null, plus negation, plus rounding, plus 1 for good measure. Hopefully I did not err: do some testing.
Also use snprintf instead of sprintf while you are at it: buffer overflows are not to be toyed with.
The next problem is that "hello" is not a std::string, It is a char const[6] -- an array of 6 char. It can be converted tomstd::string, but +1 will instead convert it to a pointer to the first character, then +1 it to the 2nd character.
Cast it to std::string before.
Finally, it is ambiguous in the standard (really) of pverloading an operator on std::string + int is legal. It is definitely poor practice, as you cannot do it in std legally, and you should overload operators in the type's namespace (so ADL works): these two conflict. On top of that, if std in the future adds such a + your code starts behaving strangely. On top of that, operators are part of a class's interface, and modifying the interface of a class you do not 'own' is rude and a bad habit.
Write your own string class that owns a std::string rather. Or a string view.
Finally, consider telling your compiler to use c++11, you probably just need to pass a flag to it like -std=c++11.
std::string s1("h1");
std::string s2("2");
s1 += s2;
If you are using C++11 compatible compiler you can convert int to string like this:
int i = 2;
std::string s = std::to_string(i);
If you are using Boost library:
#include <boost/lexical_cast.hpp>
int i = 2;
std::string s = boost::lexical_cast<std::string>(i);
Please do not use raw char pointers in C++ for strings.
overloading the operator+ on other than your own types it at best dangerous.
Just use std::to_string in conjunction with operator+ or +=, e.g.
std::string x = "hi";
x += std::to_string(2);
C++14 introduces a user-defined literal that takes a string literal (conversions are applied to make this a pointer) and returns a std::string. In C++11, you can just write your own (this is taken from libstdc++):
inline std::string
operator""_s(const char* str, size_t len)
{
return std::string{str, len};
}
(Note: UDLs without a preceding underscore are reserved names)
And you can use it like this:
// Assumes operator+ is overloaded
print("die"_s + 1);
Demo
"die" is not a std::string. It's a string literal.
Thus when you add 1 to the string literal, it decays to a const char* and the + 1 simply increments that pointer — to next char, 'i'.
Then you call print with the incremented pointer, which causes a std::string to be constructed using that pointer. Since it pointed to the 'i' character, to constructed string is initialized to "ie".
You must first make a std::string out of your string literal to make it call your operator+:
std::cout << std::string("die") + 1;
And then make a few fixes to your operator+:
string operator+ (string stuff, int why) {
return stuff.append(to_string(why));
}
Now it works.

Convert built-in data type to std::string: memcpy vs snprintf

I have referred to the relevant question and other posts before this. I am also aware that std::to_string() is the best way (but it's not available in few platforms).
While experimenting, I came across a weird issue with memcpy(). For the example sake, assume that we always pass built-in data types (int, char, long) to below function:
template<typename T>
std::string to_string (const T& value)
{
std::string s(16, 0); // Max size captured
::memcpy(&s[0], &value, sizeof(value));
return s;
}
Running this function individually in a sample program works fine. But while plugging into a bigger code base, somehow it gives weird results! i.e. it gives spurious values. (Ubuntu 14.10, g++4.9 -std=c++11)
However, if I convert the above program using sprintf(), it works fine.
template<typename T>
std::string to_string (const T& value)
{
std::string s(16, 0); // Max size captured
s[::snprintf(&s[0], "%d", value)] = 0;
return s;
}
Question:
Am I touching undefined behavior with memcpy() (or even
sprintf())?
Would byte ordering influence this code?
To recap, yes, you do not want to use memcpy(). Using snprintf() you avoid having to convert the number to ASCII yourself. Something like this would probably be preferable though:
template<typename T>
std::string to_string (const T& value)
{
char buf[16];
::snprintf(buf, sizeof(buf), "%d", value);
// ^-- size was missing in your example
return buf;
}
However, you have a big flow in this function because you cannot know what T is going to be. It could be a double and "%d" won't work as expected. Similarly, it could be a string (char const *).
If you want to manually convert a number to ASCII you can use a loop, something like this:
template<typename T>
std::string to_string (T value)
{
char buf[16]; // any int number is less than 16 characters
char *s = buf + sizeof(buf);
*--s = '\0';
do
{
*--s = value % 10 + '0'; // conversion to ASCII, 1 digit at a time
value /= 10;
}
while(value > 0);
return s;
}
WARNING: that function does not properly handle negative numbers. I'll let that one as an exercise for you to handle as required.
Now, if you want to use a C++ way that should work on all systems you mentioned, without boost or C++11.
template<typename T>
std::string to_string (T const& value)
{
std::stringstream ss;
ss << value;
return ss.str();
}
In this case the stringstream knows how to handle T whatever T is, numbers, objects, etc. as long as those things understand the << as in std::cout << "Hello!" << std::endl;.
If you check out one of my project, named as2js, you'd see a file named include/as2js/node.h which declare something like this:
std::ostream& operator << (std::ostream& out, Node const& node);
That means you can later create a node and print it like this:
Node n;
std::out << n << std::endl;
This means your to_string() function would work with my Node objects.
You can find the implementation of all of that under lib/node_display.cpp

How to convert a number to string and vice versa in C++

Since this question gets asked about every week, this FAQ might help a lot of users.
How to convert an integer to a string in C++
how to convert a string into an integer in C++
how to convert a floating-point number to a string in C++
how to convert a string to a floating-point number in C++
Update for C++11
As of the C++11 standard, string-to-number conversion and vice-versa are built in into the standard library. All the following functions are present in <string> (as per paragraph 21.5).
string to numeric
float stof(const string& str, size_t *idx = 0);
double stod(const string& str, size_t *idx = 0);
long double stold(const string& str, size_t *idx = 0);
int stoi(const string& str, size_t *idx = 0, int base = 10);
long stol(const string& str, size_t *idx = 0, int base = 10);
unsigned long stoul(const string& str, size_t *idx = 0, int base = 10);
long long stoll(const string& str, size_t *idx = 0, int base = 10);
unsigned long long stoull(const string& str, size_t *idx = 0, int base = 10);
Each of these take a string as input and will try to convert it to a number. If no valid number could be constructed, for example because there is no numeric data or the number is out-of-range for the type, an exception is thrown (std::invalid_argument or std::out_of_range).
If conversion succeeded and idx is not 0, idx will contain the index of the first character that was not used for decoding. This could be an index behind the last character.
Finally, the integral types allow to specify a base, for digits larger than 9, the alphabet is assumed (a=10 until z=35). You can find more information about the exact formatting that can parsed here for floating-point numbers, signed integers and unsigned integers.
Finally, for each function there is also an overload that accepts a std::wstring as it's first parameter.
numeric to string
string to_string(int val);
string to_string(unsigned val);
string to_string(long val);
string to_string(unsigned long val);
string to_string(long long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string(long double val);
These are more straightforward, you pass the appropriate numeric type and you get a string back. For formatting options you should go back to the C++03 stringsream option and use stream manipulators, as explained in an other answer here.
As noted in the comments these functions fall back to a default mantissa precision that is likely not the maximum precision. If more precision is required for your application it's also best to go back to other string formatting procedures.
There are also similar functions defined that are named to_wstring, these will return a std::wstring.
How to convert a number to a string in C++03
Do not use the itoa or itof functions because they are non-standard and therefore not portable.
Use string streams
#include <sstream> //include this to use string streams
#include <string>
int main()
{
int number = 1234;
std::ostringstream ostr; //output string stream
ostr << number; //use the string stream just like cout,
//except the stream prints not to stdout but to a string.
std::string theNumberString = ostr.str(); //the str() function of the stream
//returns the string.
//now theNumberString is "1234"
}
Note that you can use string streams also to convert floating-point numbers to string, and also to format the string as you wish, just like with cout
std::ostringstream ostr;
float f = 1.2;
int i = 3;
ostr << f << " + " i << " = " << f + i;
std::string s = ostr.str();
//now s is "1.2 + 3 = 4.2"
You can use stream manipulators, such as std::endl, std::hex and functions std::setw(), std::setprecision() etc. with string streams in exactly the same manner as with cout
Do not confuse std::ostringstream with std::ostrstream. The latter is deprecated
Use boost lexical cast. If you are not familiar with boost, it is a good idea to start with a small library like this lexical_cast. To download and install boost and its documentation go here. Although boost isn't in C++ standard many libraries of boost get standardized eventually and boost is widely considered of the best C++ libraries.
Lexical cast uses streams underneath, so basically this option is the same as the previous one, just less verbose.
#include <boost/lexical_cast.hpp>
#include <string>
int main()
{
float f = 1.2;
int i = 42;
std::string sf = boost::lexical_cast<std::string>(f); //sf is "1.2"
std::string si = boost::lexical_cast<std::string>(i); //sf is "42"
}
How to convert a string to a number in C++03
The most lightweight option, inherited from C, is the functions atoi (for integers (alphabetical to integer)) and atof (for floating-point values (alphabetical to float)). These functions take a C-style string as an argument (const char *) and therefore their usage may be considered a not exactly good C++ practice. cplusplus.com has easy-to-understand documentation on both atoi and atof including how they behave in case of bad input. However the link contains an error in that according to the standard if the input number is too large to fit in the target type, the behavior is undefined.
#include <cstdlib> //the standard C library header
#include <string>
int main()
{
std::string si = "12";
std::string sf = "1.2";
int i = atoi(si.c_str()); //the c_str() function "converts"
double f = atof(sf.c_str()); //std::string to const char*
}
Use string streams (this time input string stream, istringstream). Again, istringstream is used just like cin. Again, do not confuse istringstream with istrstream. The latter is deprecated.
#include <sstream>
#include <string>
int main()
{
std::string inputString = "1234 12.3 44";
std::istringstream istr(inputString);
int i1, i2;
float f;
istr >> i1 >> f >> i2;
//i1 is 1234, f is 12.3, i2 is 44
}
Use boost lexical cast.
#include <boost/lexical_cast.hpp>
#include <string>
int main()
{
std::string sf = "42.2";
std::string si = "42";
float f = boost::lexical_cast<float>(sf); //f is 42.2
int i = boost::lexical_cast<int>(si); //i is 42
}
In case of a bad input, lexical_cast throws an exception of type boost::bad_lexical_cast
In C++17, new functions std::to_chars and std::from_chars are introduced in header charconv.
std::to_chars is locale-independent, non-allocating,
and non-throwing.
Only a small subset of formatting policies used by
other libraries (such as std::sprintf) is provided.
From std::to_chars, same for std::from_chars.
The guarantee that std::from_chars can recover
every floating-point value formatted
by to_chars exactly is only provided if both
functions are from the same implementation
// See en.cppreference.com for more information, including format control.
#include <cstdio>
#include <cstddef>
#include <cstdlib>
#include <cassert>
#include <charconv>
using Type = /* Any fundamental type */ ;
std::size_t buffer_size = /* ... */ ;
[[noreturn]] void report_and_exit(int ret, const char *output) noexcept
{
std::printf("%s\n", output);
std::exit(ret);
}
void check(const std::errc &ec) noexcept
{
if (ec ==  std::errc::value_too_large)
report_and_exit(1, "Failed");
}
int main() {
char buffer[buffer_size];
Type val_to_be_converted, result_of_converted_back;
auto result1 = std::to_chars(buffer, buffer + buffer_size, val_to_be_converted);
check(result1.ec);
*result1.ptr = '\0';
auto result2 = std::from_chars(buffer, result1.ptr, result_of_converted_back);
check(result2.ec);
assert(val_to_be_converted == result_of_converted_back);
report_and_exit(0, buffer);
}
Although it's not fully implemented by compilers, it definitely will be implemented.
I stole this convienent class from somewhere here at StackOverflow to convert anything streamable to a string:
// make_string
class make_string {
public:
template <typename T>
make_string& operator<<( T const & val ) {
buffer_ << val;
return *this;
}
operator std::string() const {
return buffer_.str();
}
private:
std::ostringstream buffer_;
};
And then you use it as;
string str = make_string() << 6 << 8 << "hello";
Quite nifty!
Also I use this function to convert strings to anything streamable, althrough its not very safe if you try to parse a string not containing a number;
(and its not as clever as the last one either)
// parse_string
template <typename RETURN_TYPE, typename STRING_TYPE>
RETURN_TYPE parse_string(const STRING_TYPE& str) {
std::stringstream buf;
buf << str;
RETURN_TYPE val;
buf >> val;
return val;
}
Use as:
int x = parse_string<int>("78");
You might also want versions for wstrings.
#include <iostream>
#include <string.h>
using namespace std;
int main() {
string s="000101";
cout<<s<<"\n";
int a = stoi(s);
cout<<a<<"\n";
s=to_string(a);
s+='1';
cout<<s;
return 0;
}
Output:
000101
101
1011

converting _int64 to a string

I had a question when providing an API
if I ask for them to give me a _int64 10 digit hexadecimal number but my function internally takes strings how do I effectively convert that...
as of right now I was just using string internally but for compatibility reasons i was using char* c style so that give any system 32 or 64 it wouldn't matter. Is that the accurate thing to do? or am i wrong?
is there a problem using char* vs _int64?
C++11 standardized the std::to_string function:
#include <string>
int main()
{
int64_t value = 128;
std::string asString = std::to_string(value);
return 0;
}
#include <string>
#include <sstream>
int main()
{
std::stringstream stream;
__int64 value(1000000000);
stream << value;
std::string strValue(stream.str());
return 0;
}
The best option is to change the function to not use strings anymore so you can pass the original __int64 as-is. __int64 works the same in 32-bit and 64-bit systems.
If you have to convert to a string, there are several options. Steve showed you how to use a stringstream, which is the C++ way to do it. You can also use the C sprintf() or _i64toa() functions:
__int64 value = ...;
char buffer[20];
sprintf(buffer, "%Ld", value);
__int64 value = ...;
char buffer[20];
_i64toa(value, buffer, 10);