How to concatenate a std::string and an int - c++
I thought this would be really simple, but it's presenting some difficulties. If I have
std::string name = "John";
int age = 21;
How do I combine them to get a single string "John21"?
In alphabetical order:
std::string name = "John";
int age = 21;
std::string result;
// 1. with Boost
result = name + boost::lexical_cast<std::string>(age);
// 2. with C++11
result = name + std::to_string(age);
// 3. with FastFormat.Format
fastformat::fmt(result, "{0}{1}", name, age);
// 4. with FastFormat.Write
fastformat::write(result, name, age);
// 5. with the {fmt} library
result = fmt::format("{}{}", name, age);
// 6. with IOStreams
std::stringstream sstm;
sstm << name << age;
result = sstm.str();
// 7. with itoa
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + itoa(age, numstr, 10);
// 8. with sprintf
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", age);
result = name + numstr;
// 9. with STLSoft's integer_to_string
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + stlsoft::integer_to_string(numstr, 21, age);
// 10. with STLSoft's winstl::int_to_string()
result = name + winstl::int_to_string(age);
// 11. With Poco NumberFormatter
result = name + Poco::NumberFormatter().format(age);
is safe, but slow; requires Boost (header-only); most/all platforms
is safe, requires C++11 (to_string() is already included in #include <string>)
is safe, and fast; requires FastFormat, which must be compiled; most/all platforms
(ditto)
is safe, and fast; requires the {fmt} library, which can either be compiled or used in a header-only mode; most/all platforms
safe, slow, and verbose; requires #include <sstream> (from standard C++)
is brittle (you must supply a large enough buffer), fast, and verbose; itoa() is a non-standard extension, and not guaranteed to be available for all platforms
is brittle (you must supply a large enough buffer), fast, and verbose; requires nothing (is standard C++); all platforms
is brittle (you must supply a large enough buffer), probably the fastest-possible conversion, verbose; requires STLSoft (header-only); most/all platforms
safe-ish (you don't use more than one int_to_string() call in a single statement), fast; requires STLSoft (header-only); Windows-only
is safe, but slow; requires Poco C++ ; most/all platforms
In C++11, you can use std::to_string, e.g.:
auto result = name + std::to_string( age );
If you have Boost, you can convert the integer to a string using boost::lexical_cast<std::string>(age).
Another way is to use stringstreams:
std::stringstream ss;
ss << age;
std::cout << name << ss.str() << std::endl;
A third approach would be to use sprintf or snprintf from the C library.
char buffer[128];
snprintf(buffer, sizeof(buffer), "%s%d", name.c_str(), age);
std::cout << buffer << std::endl;
Other posters suggested using itoa. This is NOT a standard function, so your code will not be portable if you use it. There are compilers that don't support it.
#include <iostream>
#include <sstream>
std::ostringstream o;
o << name << age;
std::cout << o.str();
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string itos(int i) // convert int to string
{
stringstream s;
s << i;
return s.str();
}
Shamelessly stolen from http://www.research.att.com/~bs/bs_faq2.html.
This is the easiest way:
string s = name + std::to_string(age);
If you have C++11, you can use std::to_string.
Example:
std::string name = "John";
int age = 21;
name += std::to_string(age);
std::cout << name;
Output:
John21
It seems to me that the simplest answer is to use the sprintf function:
sprintf(outString,"%s%d",name,age);
#include <string>
#include <sstream>
using namespace std;
string concatenate(std::string const& name, int i)
{
stringstream s;
s << name << i;
return s.str();
}
#include <sstream>
template <class T>
inline std::string to_string (const T& t)
{
std::stringstream ss;
ss << t;
return ss.str();
}
Then your usage would look something like this
std::string szName = "John";
int numAge = 23;
szName += to_string<int>(numAge);
cout << szName << endl;
Googled [and tested :p ]
This problem can be done in many ways. I will show it in two ways:
Convert the number to string using to_string(i).
Using string streams.
Code:
#include <string>
#include <sstream>
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int main() {
string name = "John";
int age = 21;
string answer1 = "";
// Method 1). string s1 = to_string(age).
string s1=to_string(age); // Know the integer get converted into string
// where as we know that concatenation can easily be done using '+' in C++
answer1 = name + s1;
cout << answer1 << endl;
// Method 2). Using string streams
ostringstream s2;
s2 << age;
string s3 = s2.str(); // The str() function will convert a number into a string
string answer2 = ""; // For concatenation of strings.
answer2 = name + s3;
cout << answer2 << endl;
return 0;
}
In C++20 you'll be able to do:
auto result = std::format("{}{}", name, age);
In the meantime you can use the {fmt} library, std::format is based on:
auto result = fmt::format("{}{}", name, age);
Disclaimer: I'm the author of the {fmt} library and C++20 std::format.
If you'd like to use + for concatenation of anything which has an output operator, you can provide a template version of operator+:
template <typename L, typename R> std::string operator+(L left, R right) {
std::ostringstream os;
os << left << right;
return os.str();
}
Then you can write your concatenations in a straightforward way:
std::string foo("the answer is ");
int i = 42;
std::string bar(foo + i);
std::cout << bar << std::endl;
Output:
the answer is 42
This isn't the most efficient way, but you don't need the most efficient way unless you're doing a lot of concatenation inside a loop.
If you are using MFC, you can use a CString
CString nameAge = "";
nameAge.Format("%s%d", "John", 21);
Managed C++ also has a
string formatter.
As a one liner: name += std::to_string(age);
The std::ostringstream is a good method, but sometimes this additional trick might get handy transforming the formatting to a one-liner:
#include <sstream>
#define MAKE_STRING(tokens) /****************/ \
static_cast<std::ostringstream&>( \
std::ostringstream().flush() << tokens \
).str() \
/**/
Now you can format strings like this:
int main() {
int i = 123;
std::string message = MAKE_STRING("i = " << i);
std::cout << message << std::endl; // prints: "i = 123"
}
As a Qt-related question was closed in favour of this one, here's how to do it using Qt:
QString string = QString("Some string %1 with an int somewhere").arg(someIntVariable);
string.append(someOtherIntVariable);
The string variable now has someIntVariable's value in place of %1 and someOtherIntVariable's value at the end.
There are more options possible to use to concatenate integer (or other numerric object) with string. It is Boost.Format
#include <boost/format.hpp>
#include <string>
int main()
{
using boost::format;
int age = 22;
std::string str_age = str(format("age is %1%") % age);
}
and Karma from Boost.Spirit (v2)
#include <boost/spirit/include/karma.hpp>
#include <iterator>
#include <string>
int main()
{
using namespace boost::spirit;
int age = 22;
std::string str_age("age is ");
std::back_insert_iterator<std::string> sink(str_age);
karma::generate(sink, int_, age);
return 0;
}
Boost.Spirit Karma claims to be one of the fastest option for integer to string conversion.
std::ostringstream
#include <sstream>
std::ostringstream s;
s << "John " << age;
std::string query(s.str());
std::to_string (C++11)
std::string query("John " + std::to_string(age));
boost::lexical_cast
#include <boost/lexical_cast.hpp>
std::string query("John " + boost::lexical_cast<std::string>(age));
Here is an implementation of how to append an int to a string using the parsing and formatting facets from the IOStreams library.
#include <iostream>
#include <locale>
#include <string>
template <class Facet>
struct erasable_facet : Facet
{
erasable_facet() : Facet(1) { }
~erasable_facet() { }
};
void append_int(std::string& s, int n)
{
erasable_facet<std::num_put<char,
std::back_insert_iterator<std::string>>> facet;
std::ios str(nullptr);
facet.put(std::back_inserter(s), str,
str.fill(), static_cast<unsigned long>(n));
}
int main()
{
std::string str = "ID: ";
int id = 123;
append_int(str, id);
std::cout << str; // ID: 123
}
Common Answer: itoa()
This is bad. itoa is non-standard, as pointed out here.
You can concatenate int to string by using the given below simple trick, but note that this only works when integer is of single digit. Otherwise, add integer digit by digit to that string.
string name = "John";
int age = 5;
char temp = 5 + '0';
name = name + temp;
cout << name << endl;
Output: John5
There is a function I wrote, which takes the int number as the parameter, and convert it to a string literal. This function is dependent on another function that converts a single digit to its char equivalent:
char intToChar(int num)
{
if (num < 10 && num >= 0)
{
return num + 48;
//48 is the number that we add to an integer number to have its character equivalent (see the unsigned ASCII table)
}
else
{
return '*';
}
}
string intToString(int num)
{
int digits = 0, process, single;
string numString;
process = num;
// The following process the number of digits in num
while (process != 0)
{
single = process % 10; // 'single' now holds the rightmost portion of the int
process = (process - single)/10;
// Take out the rightmost number of the int (it's a zero in this portion of the int), then divide it by 10
// The above combination eliminates the rightmost portion of the int
digits ++;
}
process = num;
// Fill the numString with '*' times digits
for (int i = 0; i < digits; i++)
{
numString += '*';
}
for (int i = digits-1; i >= 0; i--)
{
single = process % 10;
numString[i] = intToChar ( single);
process = (process - single) / 10;
}
return numString;
}
In C++ 20 you can have a variadic lambda that does concatenate arbitrary streamable types to a string in a few lines:
auto make_string=[os=std::ostringstream{}](auto&& ...p) mutable
{
(os << ... << std::forward<decltype(p)>(p) );
return std::move(os).str();
};
int main() {
std::cout << make_string("Hello world: ",4,2, " is ", 42.0);
}
see https://godbolt.org/z/dEe9h75eb
using move(os).str() guarantees that the ostringstream object's stringbuffer is empty next time the lambda is called.
You can use the C function itoa() like this:
char buf[3];
itoa(age, buf, 10);
name += buf;
Related
How to concatenate strings in an output function?
Some languages have easy ways of doing this, but my question revolves in C and C++. I wanna do something like this in Java: public class sandbox { public static void main(String[] args) { System.out.println("Thank" + " you!"); } } And transfer it in C: #include <stdio.h> int main() { /* The easiest way is like this: char *text1 = "Thank"; char *text2 = " you"; printf("%s%s\n", text1, text2); */ printf("Thank" + " you."); // What I really want to do } How do I concatenate strings in a language like this?
You use just nothing: puts ("Thank" " you.");
Concatenating strings is not that easy in C unfortunately, here's how to do it most succinctly: char *text1 = "Thank"; char *text2 = " you"; char *text_concat = malloc(strlen(text1) + strlen(text2) + 1); assert(text_concat); text_concat = strcpy(text_concat, text1); text_concat = strcat(text_concat, text2); printf("%s\n", text_concat); free(text_concat);
What I have understood from your question, hope the below solution will answer your question. #include <stdio.h> int main() { char s1[100] = "Thank ", s2[] = "You"; int length, j; // store length of s1 in the length variable length = 0; while (s1[length] != '\0') { ++length; } // concatenate s2 to s1 for (j = 0; s2[j] != '\0'; ++j, ++length) { s1[length] = s2[j]; } // terminating the s1 string s1[length] = '\0'; printf("After concatenation: %s",s1); return 0; } In C++, you can easily concatenate two string it by adding two string with a + operator. #include <iostream> using namespace std; int main() { string s1, s2, result; cout << "Enter string s1: "; cin>>s1; cout << "Enter string s2: "; cin>>s2; result = s1 + s2; cout << "After concatenation: = "<< result; return 0; }
This is a concatenation, but is a constant or compile time concatenation, you can't concatenate strings like that, but in case you need to split a string constant in multiple parts is ok: ... printf("Thank" " you."); // What I really want to do ... For dynamic, runtime concatenation you need strcat like strcat(text1, text2); First you must assure that you have enough memory in target string, see this link http://www.cplusplus.com/reference/cstring/strcat/ Ok, that was the C way, but C++ has STL with std::string #include <iostream> #include <string> using namespace std; int main() { string str1 = "hello ", str2 = "world"; cout<< str1 + str2<< endl; return 0; }
It is not possible in C to do something like printf("Thank" + " you."); because C doesn't support Operator Overloading Unlike C++. You can refer Is it possible to overload operators in C?
C++ compile error about operater-overloading, type-conversion, and int promotion [duplicate]
I thought this would be really simple, but it's presenting some difficulties. If I have std::string name = "John"; int age = 21; How do I combine them to get a single string "John21"?
In alphabetical order: std::string name = "John"; int age = 21; std::string result; // 1. with Boost result = name + boost::lexical_cast<std::string>(age); // 2. with C++11 result = name + std::to_string(age); // 3. with FastFormat.Format fastformat::fmt(result, "{0}{1}", name, age); // 4. with FastFormat.Write fastformat::write(result, name, age); // 5. with the {fmt} library result = fmt::format("{}{}", name, age); // 6. with IOStreams std::stringstream sstm; sstm << name << age; result = sstm.str(); // 7. with itoa char numstr[21]; // enough to hold all numbers up to 64-bits result = name + itoa(age, numstr, 10); // 8. with sprintf char numstr[21]; // enough to hold all numbers up to 64-bits sprintf(numstr, "%d", age); result = name + numstr; // 9. with STLSoft's integer_to_string char numstr[21]; // enough to hold all numbers up to 64-bits result = name + stlsoft::integer_to_string(numstr, 21, age); // 10. with STLSoft's winstl::int_to_string() result = name + winstl::int_to_string(age); // 11. With Poco NumberFormatter result = name + Poco::NumberFormatter().format(age); is safe, but slow; requires Boost (header-only); most/all platforms is safe, requires C++11 (to_string() is already included in #include <string>) is safe, and fast; requires FastFormat, which must be compiled; most/all platforms (ditto) is safe, and fast; requires the {fmt} library, which can either be compiled or used in a header-only mode; most/all platforms safe, slow, and verbose; requires #include <sstream> (from standard C++) is brittle (you must supply a large enough buffer), fast, and verbose; itoa() is a non-standard extension, and not guaranteed to be available for all platforms is brittle (you must supply a large enough buffer), fast, and verbose; requires nothing (is standard C++); all platforms is brittle (you must supply a large enough buffer), probably the fastest-possible conversion, verbose; requires STLSoft (header-only); most/all platforms safe-ish (you don't use more than one int_to_string() call in a single statement), fast; requires STLSoft (header-only); Windows-only is safe, but slow; requires Poco C++ ; most/all platforms
In C++11, you can use std::to_string, e.g.: auto result = name + std::to_string( age );
If you have Boost, you can convert the integer to a string using boost::lexical_cast<std::string>(age). Another way is to use stringstreams: std::stringstream ss; ss << age; std::cout << name << ss.str() << std::endl; A third approach would be to use sprintf or snprintf from the C library. char buffer[128]; snprintf(buffer, sizeof(buffer), "%s%d", name.c_str(), age); std::cout << buffer << std::endl; Other posters suggested using itoa. This is NOT a standard function, so your code will not be portable if you use it. There are compilers that don't support it.
#include <iostream> #include <sstream> std::ostringstream o; o << name << age; std::cout << o.str();
#include <iostream> #include <string> #include <sstream> using namespace std; string itos(int i) // convert int to string { stringstream s; s << i; return s.str(); } Shamelessly stolen from http://www.research.att.com/~bs/bs_faq2.html.
This is the easiest way: string s = name + std::to_string(age);
If you have C++11, you can use std::to_string. Example: std::string name = "John"; int age = 21; name += std::to_string(age); std::cout << name; Output: John21
It seems to me that the simplest answer is to use the sprintf function: sprintf(outString,"%s%d",name,age);
#include <string> #include <sstream> using namespace std; string concatenate(std::string const& name, int i) { stringstream s; s << name << i; return s.str(); }
#include <sstream> template <class T> inline std::string to_string (const T& t) { std::stringstream ss; ss << t; return ss.str(); } Then your usage would look something like this std::string szName = "John"; int numAge = 23; szName += to_string<int>(numAge); cout << szName << endl; Googled [and tested :p ]
This problem can be done in many ways. I will show it in two ways: Convert the number to string using to_string(i). Using string streams. Code: #include <string> #include <sstream> #include <bits/stdc++.h> #include <iostream> using namespace std; int main() { string name = "John"; int age = 21; string answer1 = ""; // Method 1). string s1 = to_string(age). string s1=to_string(age); // Know the integer get converted into string // where as we know that concatenation can easily be done using '+' in C++ answer1 = name + s1; cout << answer1 << endl; // Method 2). Using string streams ostringstream s2; s2 << age; string s3 = s2.str(); // The str() function will convert a number into a string string answer2 = ""; // For concatenation of strings. answer2 = name + s3; cout << answer2 << endl; return 0; }
In C++20 you'll be able to do: auto result = std::format("{}{}", name, age); In the meantime you can use the {fmt} library, std::format is based on: auto result = fmt::format("{}{}", name, age); Disclaimer: I'm the author of the {fmt} library and C++20 std::format.
If you'd like to use + for concatenation of anything which has an output operator, you can provide a template version of operator+: template <typename L, typename R> std::string operator+(L left, R right) { std::ostringstream os; os << left << right; return os.str(); } Then you can write your concatenations in a straightforward way: std::string foo("the answer is "); int i = 42; std::string bar(foo + i); std::cout << bar << std::endl; Output: the answer is 42 This isn't the most efficient way, but you don't need the most efficient way unless you're doing a lot of concatenation inside a loop.
If you are using MFC, you can use a CString CString nameAge = ""; nameAge.Format("%s%d", "John", 21); Managed C++ also has a string formatter.
As a one liner: name += std::to_string(age);
The std::ostringstream is a good method, but sometimes this additional trick might get handy transforming the formatting to a one-liner: #include <sstream> #define MAKE_STRING(tokens) /****************/ \ static_cast<std::ostringstream&>( \ std::ostringstream().flush() << tokens \ ).str() \ /**/ Now you can format strings like this: int main() { int i = 123; std::string message = MAKE_STRING("i = " << i); std::cout << message << std::endl; // prints: "i = 123" }
As a Qt-related question was closed in favour of this one, here's how to do it using Qt: QString string = QString("Some string %1 with an int somewhere").arg(someIntVariable); string.append(someOtherIntVariable); The string variable now has someIntVariable's value in place of %1 and someOtherIntVariable's value at the end.
There are more options possible to use to concatenate integer (or other numerric object) with string. It is Boost.Format #include <boost/format.hpp> #include <string> int main() { using boost::format; int age = 22; std::string str_age = str(format("age is %1%") % age); } and Karma from Boost.Spirit (v2) #include <boost/spirit/include/karma.hpp> #include <iterator> #include <string> int main() { using namespace boost::spirit; int age = 22; std::string str_age("age is "); std::back_insert_iterator<std::string> sink(str_age); karma::generate(sink, int_, age); return 0; } Boost.Spirit Karma claims to be one of the fastest option for integer to string conversion.
std::ostringstream #include <sstream> std::ostringstream s; s << "John " << age; std::string query(s.str()); std::to_string (C++11) std::string query("John " + std::to_string(age)); boost::lexical_cast #include <boost/lexical_cast.hpp> std::string query("John " + boost::lexical_cast<std::string>(age));
Here is an implementation of how to append an int to a string using the parsing and formatting facets from the IOStreams library. #include <iostream> #include <locale> #include <string> template <class Facet> struct erasable_facet : Facet { erasable_facet() : Facet(1) { } ~erasable_facet() { } }; void append_int(std::string& s, int n) { erasable_facet<std::num_put<char, std::back_insert_iterator<std::string>>> facet; std::ios str(nullptr); facet.put(std::back_inserter(s), str, str.fill(), static_cast<unsigned long>(n)); } int main() { std::string str = "ID: "; int id = 123; append_int(str, id); std::cout << str; // ID: 123 }
Common Answer: itoa() This is bad. itoa is non-standard, as pointed out here.
You can concatenate int to string by using the given below simple trick, but note that this only works when integer is of single digit. Otherwise, add integer digit by digit to that string. string name = "John"; int age = 5; char temp = 5 + '0'; name = name + temp; cout << name << endl; Output: John5
There is a function I wrote, which takes the int number as the parameter, and convert it to a string literal. This function is dependent on another function that converts a single digit to its char equivalent: char intToChar(int num) { if (num < 10 && num >= 0) { return num + 48; //48 is the number that we add to an integer number to have its character equivalent (see the unsigned ASCII table) } else { return '*'; } } string intToString(int num) { int digits = 0, process, single; string numString; process = num; // The following process the number of digits in num while (process != 0) { single = process % 10; // 'single' now holds the rightmost portion of the int process = (process - single)/10; // Take out the rightmost number of the int (it's a zero in this portion of the int), then divide it by 10 // The above combination eliminates the rightmost portion of the int digits ++; } process = num; // Fill the numString with '*' times digits for (int i = 0; i < digits; i++) { numString += '*'; } for (int i = digits-1; i >= 0; i--) { single = process % 10; numString[i] = intToChar ( single); process = (process - single) / 10; } return numString; }
In C++ 20 you can have a variadic lambda that does concatenate arbitrary streamable types to a string in a few lines: auto make_string=[os=std::ostringstream{}](auto&& ...p) mutable { (os << ... << std::forward<decltype(p)>(p) ); return std::move(os).str(); }; int main() { std::cout << make_string("Hello world: ",4,2, " is ", 42.0); } see https://godbolt.org/z/dEe9h75eb using move(os).str() guarantees that the ostringstream object's stringbuffer is empty next time the lambda is called.
You can use the C function itoa() like this: char buf[3]; itoa(age, buf, 10); name += buf;
Parse a string into two double
I have a string that is in the format #########s###.## where #### is just a few numbers, and the second piece is usually a decimal, but not always. I need to break the two number pieces apart, and set them as two doubles(or some other valid number type. I can only use standard methods for this, as the server it's being run on only has standard modules. I can currently grab the second piece using find and substr, but can't figure out how to get the first piece. I still haven't done anything that changes the second piece into a numerical type, but hopefully that is much easier. here's what I have: string symbol,pieces; fin >> pieces; //pieces is a string of the type i mentioned #####s###.## unsigned pos; pos = pieces.find("s"); string capitals = pieces.substr(pos+1); cout << "Price of stock " << symbol << " is " << capitals << endl;
istringstream makes it easy. #include <iostream> #include <sstream> #include <string> int main(int argc, char* argv[]) { std::string input("123456789s123.45"); std::istringstream output(input); double part1; double part2; output >> part1; char c; // Throw away the "s" output >> c; output >> part2; std::cout << part1 << ", " << part2 << std::endl; return 0; }
You can specify a count along with an offset when calling substr: string first = pieces.substr(0, pos); string second = pieces.substr(pos + 1);
You can do the same thing as you did for the second part: unsigned pos; pos = pieces.find("s"); string firstPart = pieces.substr(0,pos);
This code will split the string as you desire and convert them to double, it could easily be changed to convert to float as well: #include <iostream> #include <sstream> #include <string> #include <stdexcept> class BadConversion : public std::runtime_error { public: BadConversion(std::string const& s) : std::runtime_error(s) { } }; inline double convertToDouble(std::string const& s, bool failIfLeftoverChars = true) { std::istringstream i(s); double x; char c; if (!(i >> x) || (failIfLeftoverChars && i.get(c))) throw BadConversion("convertToDouble(\"" + s + "\")"); return x; } int main() { std::string symbol,pieces; std::cin >> pieces; //pieces is a string of the type i mentioned #####s###.## unsigned pos; pos = pieces.find("s"); std::string first = pieces.substr(0, pos); std::string second = pieces.substr(pos + 1); std::cout << "first: " << first << " second " << second << std::endl; double d1 = convertToDouble(first), d2 = convertToDouble(second) ; std::cout << d1 << " " << d2 << std::endl ; } Just for reference, I took the conversion code from one of my previous answers.
Grabbing the first piece is easy: string firstpiece = pieces.substr(0, pos); As for converting to numeric types, I find sscanf() to be particularly useful for that: #include <cstdio> std::string pieces; fin >> pieces; //pieces is a string of the type i mentioned #####s###.## double firstpiece = 0.0, capitals = 0.0; std::sscanf(pieces.c_str() "%lfs%lf", &firstpiece, &capitals); ...
Some poeple will complain that this is not C++-y but this is valid C++ char * in = "1234s23.93"; char * endptr; double d1 = strtod(in,&endptr); in = endptr + 1; double d2 = strtod(in, &endptr);
converting from strings to ints
I would like to know what is the easiest way to convert an int to C++ style string and from C++ style string to int. edit Thank you very much. When converting form string to int what happens if I pass a char string ? (ex: "abce"). Thanks & Regards, Mousey
Probably the easiest is to use operator<< and operator>> with a stringstream (you can initialize a stringstream from a string, and use the stream's .str() member to retrieve a string after writing to it. Boost has a lexical_cast that makes this particularly easy (though hardly a paragon of efficiency). Normal use would be something like int x = lexical_cast<int>(your_string);
You can change "%x" specifier to "%d" or any other format supported by sprintf. Ensure to appropriately adjust the buffer size 'buf' int main(){ char buf[sizeof(int)*2 + 1]; int x = 0x12345678; sprintf(buf, "%x", x); string str(buf); int y = atoi(str.c_str()); } EDIT 2: int main(){ char buf[sizeof(int)*2 + 1]; int x = 42; sprintf(buf, "%x", x); string str(buf); //int y = atoi(str.c_str()); int y = static_cast<int>(strtol(str.c_str(), NULL, 16)); }
This is to convert string to number. #include "stdafx.h" #include <iostream> #include <string> #include <sstream> int convert_string_to_number(const std::string& st) { std::istringstream stringinfo(st); int num = 0; stringinfo >> num; return num; } int main() { int number = 0; std::string number_as_string("425"); number = convert_string_to_number(number_as_string); std::cout << "The number is " << number << std::endl; std::cout << "Number of digits are " << number_as_string.length() << std::endl; } Like wise, the following is to convert number to string. #include "stdafx.h" #include <iostream> #include <string> #include <sstream> std::string convert_number_to_string(const int& number_to_convert) { std::ostringstream os; os << number_to_convert; return (os.str()); } int main() { int number = 425; std::string stringafterconversion; stringafterconversion = convert_number_to_string(number); std::cout << "After conversion " << stringafterconversion << std::endl; std::cout << "Number of digits are " << stringafterconversion.length() << std::endl; }
Use atoi to convert a string to an int. Use a stringstream to convert the other way.
how do i add a int to a string
i have a string and i need to add a number to it i.e a int. like: string number1 = ("dfg"); int number2 = 123; number1 += number2; this is my code: name = root_enter; // pull name from another string. size_t sz; sz = name.size(); //find the size of the string. name.resize (sz + 5, account); // add the account number. cout << name; //test the string. this works... somewhat but i only get the "*name*88888" and... i don't know why. i just need a way to add the value of a int to the end of a string
There are no in-built operators that do this. You can write your own function, overload an operator+ for a string and an int. If you use a custom function, try using a stringstream: string addi2str(string const& instr, int v) { stringstream s(instr); s << v; return s.str(); }
Use a stringstream. #include <iostream> #include <sstream> using namespace std; int main () { int a = 30; stringstream ss(stringstream::in | stringstream::out); ss << "hello world"; ss << '\n'; ss << a; cout << ss.str() << '\n'; return 0; }
You can use string streams: template<class T> std::string to_string(const T& t) { std::ostringstream ss; ss << t; return ss.str(); } // usage: std::string s("foo"); s.append(to_string(12345)); Alternatively you can use utilities like Boosts lexical_cast(): s.append(boost::lexical_cast<std::string>(12345));
Use a stringstream. int x = 29; std::stringstream ss; ss << "My age is: " << x << std::endl; std::string str = ss.str();
you can use lexecal_cast from boost, then C itoa and of course stringstream from STL