How to convert a number to string and vice versa in C++ - 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

Related

How would you concatenate "on the fly" a text+integer passing it to a function? [duplicate]

This question already has answers here:
How to concatenate a std::string and an int
(25 answers)
Closed 4 years ago.
I've a function in a library (so, that I cannot change) like this:
char mName[MAX_PARAM_NAME_LEN];
void IParam::InitBool(const char* name) {
strcpy(mName, name);
}
I'd like to pass text as Text0, Text1 (and so on) "faster", writing directly inside the function, starting from a text and an integer, without store additional variables on my own; such as:
int mIndex = 0;
InitBool("Text" + mIndex);
How would you do it? Wrap functions? Which one? Best approch? In C# thats pretty done, I find hard to do it in C++.
If your compiler supports C++17 features you could use a fold expression and string stream. The magic happens in the stringify() function which accepts zero or more arguments.
#include <iostream>
#include <sstream>
#include <string>
template <typename... Ts>
std::string stringify(const Ts&... args)
{
std::ostringstream oss;
(oss << ... << args);
return oss.str();
}
void InitBool(const char *name)
{
std::cout << name << '\n';
}
int main()
{
int mIndex = 0;
InitBool(stringify("Text", mIndex, '!', 1.0/3.0).c_str());
}
Live Demo
In C++ "Text" is a const char[N], it's not actually a string type but just an array of characters with a null character ('\0') at the end. This doesn't support any sort of string manipulation. What you need to get is a std::string, which does support many string operations. Since you need to convert mIndex to a string to begin with we can just to that and the string that represents the number will handle concatenating "Text" to it. That gives you
int mIndex = 0;
InitBool(("Text" + std::to_string(mIndex)).c_str());
The ("Text" + std::to_string(mIndex)) part gives you a temporary std::string that is "Text0" and then the .c_str() gets a const char* to that string to pass to the function.
You can wrap the ("Text" + std::to_string(mIndex)) part in a function like
std::string concat(const char* str, int val)
{
return str + std::to_string(val);
}
and then the function call would look like
InitBool(concat("Text", mIndex).c_str());

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.

How string number convert to integer number? [duplicate]

This question already has answers here:
How to convert a number to string and vice versa in C++
(5 answers)
Closed 9 years ago.
#include <iostream>
using namespace std;
int main() {
string a = "1234"; //How this string convert in integer number
system("pause");
return EXIT_SUCCESS;
}
string a = "1234";
How this convert in integer
You can use std::stoi() to convert a std::string to an int.
#include <iostream>
#include <string>
int main() {
std::string a = "1234"; //How this string convert in integer number
int b = std::stoi(a);
system("pause");
return EXIT_SUCCESS;
}
If you have C++11 and onwards, use
int n = std::stoi(a);
(Pre C++11, you could use std::strtol;)
You could use boosts lexical cast
#include <boost/lexical_cast.hpp>
std::string str_num = "12345";
int value = 0;
try
{
value = boost::lexical_cast<int>(str_num);
}
catch(boost::bad_lexical_cast &)
{
// error with conversion - calling code will deal with
}
This way you can easily modify the code to deal with float or double if your string contains those types of numeric value also
You have to use std::stoi:
#include <iostream>
#include <string>
std::string s = "123";
int number= std::stoi(s);
The C++ Standard has a special function
int stoi(const string& str, size_t *idx = 0, int base = 10);
Probably you can try this
string a = "28787" ;
int myNumber;
istringstream ( a) >> myNumber;
See or you can search for stoi function and see how it can be used. Probably It can work but never try because I dont have the compiler of c++

C++ iterator value to variable

I am using an iterator in a C++ code to retrieve records read using sqlite3 statements. I am able to display the contents pointed to by the iterator to screen using cout. How would i assign the value to a simple float or array variable.
typedef vector<vector<string> > Records;
vector< vector<string> >::iterator iter_ii;
vector<string>::iterator iter_jj;
Records records = select_stmt("SELECT density FROM Ftable where PROG=2.0");
for(iter_ii=records.begin(); iter_ii!=records.end(); iter_ii++)
{
for(iter_jj=(*iter_ii).begin(); iter_jj!=(*iter_ii).end(); iter_jj++)
{
cout << *iter_jj << endl; //This works fine and data gets displayed!
//How do i store the data pointed to by *iter_jj in a simple float variable or array?
}
}
C++ is type-safe, so you need to explicitly convert the string to the desired target type.
For float for example you could use atof:
float f = atof(iter_jj->c_str());
A more convenient alternative is Boost's lexical_cast, which works with the same syntax for all types that support extraction from an std::istream:
float f = boost::lexical_cast<float>(*iter_jj);
Note that both of these can fail in different ways if the contents of the string cannot be converted to a float in any meaningful way.
Your real problem is how to convert a string to a float. Here is one solution.
float value;
stringstream ss(*iter_jj);
if (! (ss >> value))
{
ERROR failed to convert value
}
If you have C++11 compatible compiler:
float x = stof(*iter_jj);
(Obviously x could be a variable outside of the loop).
If you don't have C++11:
stringstream ss(*iter_jj);
float x;
ss >> x;
Well since you are working with:
std::vector<std::vector<std::string> > records;
the actual question here is: how to retrieve the specific type of data from std::string object.
The good approach would be constructing and using std::istringstream object for this purpose:
float f;
std::istringstream is(*iter_jj);
if (is >> f)
{
// handle successful retrieval...
}
just don't forget to #include <sstream> :)
As for converting * to string, in c++11, you can convert integer/floats to string by calling static method to_string:string str = std::string::to_string(integer/* or float*/);
in c++98, you can write your own to_string:
#include <cstdio>
#include <cstring>
#include <cstdarg>
#include <string>
void format_aux(char* ptr, int size, const char* format, ...) {
va_list args;
va_start(args, format);
vsnprintf(ptr, size, format, args);
va_end(args);
}
#undef TO_STRING__GEN
#define TO_STRING__GEN(type, arg, size) \
std::string \
to_string(type val) { \
const int sz = size; \
char buf[sz]; \
format_aux(buf, sz, arg, val); \
return std::string(buf); \
}
TO_STRING__GEN(int, "%d", 4*sizeof(int))
TO_STRING__GEN(unsigned int, "%u", 4*sizeof(unsigned int))
TO_STRING__GEN(long, "%ld", 4*sizeof(long))
TO_STRING__GEN(unsigned long, "%lu", 4*sizeof(unsigned long))
TO_STRING__GEN(float, "%f", (std::numeric_limits<float>::max_exponent10 + 20))
TO_STRING__GEN(double, "%f", (std::numeric_limits<float>::max_exponent10 + 20))
#undef TO_STRING__GEN
*iter_jj is going to give you a std::string. In order to store that as a float, it will need to be a floating point number in string form (e.g. "1.23456") and you will need to call one of the strtof family of functions (http://en.cppreference.com/w/cpp/string/byte/strtof)

How do I convert a long to a string in 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);