Is there any function in C++ which converts all data types (double, int, short, etc) to string?
Usually you'll use the << operator, in conjunction with (for example) a std::stringstream.
http://www.boost.org/doc/libs/1_43_0/libs/conversion/lexical_cast.htm
If boost is not an option (it should always be, but just in case):
#include <sstream>
#include <string>
template<class T1, class T2>
T1 lexical_cast(const T2& value)
{
std::stringstream stream;
T1 retval;
stream << value;
stream >> retval;
return retval;
}
template<class T>
std::string to_str(const T& value)
{
return lexical_cast<std::string>(value);
}
Boost has a similar idea, but the implementation is much more efficient.
There is no built-in universal function, but boost::lexical_cast<> will do this.
Why do you need this conversion? A lot of languages have variant types which auto-convert, and this can lead to wanting that behavior in C++ even though there may be a more canonical way of implementing it.
For example if you're trying to do output, using a (string)stream of some sort is probably the way to go. If you really need to generate and manipulate a string, you can use boost::lexical_cast http://www.boost.org/doc/libs/1_43_0/libs/conversion/lexical_cast.htm.
Here is the one I use from my utility library. This was condensed from other posts here on stackoverflow, I am not claiming this as my own original code.
#include <string>
#include <sstream>
using namespace std;
template <class T>
string ToString(const T& Value) {
stringstream ss;
ss << Value;
string s = ss.str();
return s;
}
also, another handy string formatting utility I use:
#include <string>
#include <stdarg.h> /* we need va_list */
// Usage: string myString = FormatString("%s %d", "My Number =", num);
string FormatString(const char *fmt, ...) {
string retStr;
if (NULL != fmt) {
va_list marker = NULL;
va_start(marker, fmt);
size_t len = 256 + 1; // hard size set to 256
vector <char> buffer(len, '\0');
if (vsnprintf(&buffer[0], buffer.size(), fmt, marker) > 0) {
retStr = &buffer[0]; // Copy vector contents to the string
}
va_end(marker);
}
return retStr;
}
For this use stringstream.
First include the header file as #include .
Then create an object of stringstream and using stream insertion operator (<<) pass the contents you want to convert as string.
Ex:
#include <iostream>
#include <sstream>
int main(){
std::string name = "Ram";
float salary = 400.56;
std::stringstream obj;
obj << name << " salary: " << salary;
std::string s = obj.str();
std::cout << s;
}
Related
So I want to do something like
printf("%s", '\t'*3);
Im just wondering if there is a way to print something like that without looping
printf("%s%s%s", "\t", "\t", "\t"); ? Just kidding. But since you have tagged this as C++, and since I don't know what higher-level problem you are trying to solve here, have you considered just using the appropriate std::string constructor?
std::string s(3, '\t');
You can even use it with printf if you really insist...
printf("%s", std::string(3, '\t').c_str());
But why not just use std::cout?
std::cout << std::string(3, '\t');
About the "without looping" part... both printf and std::string may have loops in their implementations, of course. But that should not bother you.
assuming that you ment runtime loops and are allowed to use boost, you could create the strings at compile time using templates:
#include <iostream>
#include <boost/mpl/char.hpp>
#include <boost/mpl/string.hpp>
using namespace boost;
template <unsigned int C, int R>
struct repchrn
{
typedef typename mpl::push_back<typename repchrn<C, R - 1>::string, mpl::char_<C>>::type string;
static const char* getString() { return mpl::c_str<string>::value; }
};
template <unsigned int C>
struct repchrn<C, 0>
{
typedef mpl::string<> string;
static const char* getString() { return mpl::c_str<string>::value; }
};
int main() {
printf("%s", repchrn<'a', 5>::getString());
/* or */ std::cout << std::endl;
std::cout << repchrn<'a', 5>::getString();
}
Can I overload existing function/operator in existing class?
I was trying to do:
#include <iostream>
#include <string>
using namespace std;
string& string::operator<<(const string& str) {
this->append(str);
}
But this gives me error:
test.cpp:5: error: too few template-parameter-lists
How can I do this? Or I can't?
You can't add member functions to a class unless you modify that class' definition. Use a free function instead:
string& operator<<(string & lhs, const string & rhs) {
return lhs += rhs;
}
I defer to Benjamin's answer for creating a stream-like interface on a string object. However, you could use a stringstream instead.
#include <sstream>
std::istringstream ss;
ss << anything_you_want;
std::string s = ss.str(); // get the resulting string
ss.str(std::string()); // clear the string buffer in the stringstream.
This gives you the stream-like interface you want on a string without needing to define a new function.
This technique can be used generally to extend the functionality of a string. That is, defining a wrapper class that provides the extended functionality, and the wrapper class also provides access to the underlying string.
Use
std::ostringstream
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
std::ostringstream ss;
ss << "Hello" << " " << "world";
std::string s = ss.str();
ss.str(std::string());
cout << s << endl;
return 0;
}
https://onlinegdb.com/rkanzeniI
What is the shortest way, preferably inline-able, to convert an int to a string? Answers using stl and boost will be welcomed.
You can use std::to_string in C++11
int i = 3;
std::string str = std::to_string(i);
#include <sstream>
#include <string>
const int i = 3;
std::ostringstream s;
s << i;
const std::string i_as_string(s.str());
boost::lexical_cast<std::string>(yourint) from boost/lexical_cast.hpp
Work's for everything with std::ostream support, but is not as fast as, for example, itoa
It even appears to be faster than stringstream or scanf:
http://www.boost.org/doc/libs/1_53_0/doc/html/boost_lexical_cast/performance.html
Well, the well known way (before C++11) to do that is using the stream operator :
#include <sstream>
std::ostringstream s;
int i;
s << i;
std::string converted(s.str());
Of course, you can generalize it for any type using a template function ^^
#include <sstream>
template<typename T>
std::string toString(const T& value)
{
std::ostringstream oss;
oss << value;
return oss.str();
}
If you cannot use std::to_string from C++11, you can write it as it is defined on cppreference.com:
std::string to_string( int value )
Converts a signed decimal integer to a string with the same content as what std::sprintf(buf, "%d", value) would produce for sufficiently large buf.
Implementation
#include <cstdio>
#include <string>
#include <cassert>
std::string to_string( int x ) {
int length = snprintf( NULL, 0, "%d", x );
assert( length >= 0 );
char* buf = new char[length + 1];
snprintf( buf, length + 1, "%d", x );
std::string str( buf );
delete[] buf;
return str;
}
You can do more with it. Just use "%g" to convert float or double to string, use "%x" to convert int to hex representation, and so on.
Non-standard function, but its implemented on most common compilers:
int input = MY_VALUE;
char buffer[100] = {0};
int number_base = 10;
std::string output = itoa(input, buffer, number_base);
Update
C++11 introduced several std::to_string overloads (note that it defaults to base-10).
The following macro is not quite as compact as a single-use ostringstream or boost::lexical_cast.
But if you need conversion-to-string repeatedly in your code, this macro is more elegant in use than directly handling stringstreams or explicit casting every time.
It is also very versatile, as it converts everything supported by operator<<(), even in combination.
Definition:
#include <sstream>
#define SSTR( x ) dynamic_cast< std::ostringstream & >( \
( std::ostringstream() << std::dec << x ) ).str()
Explanation:
The std::dec is a side-effect-free way to make the anonymous ostringstream into a generic ostream so operator<<() function lookup works correctly for all types. (You get into trouble otherwise if the first argument is a pointer type.)
The dynamic_cast returns the type back to ostringstream so you can call str() on it.
Use:
#include <string>
int main()
{
int i = 42;
std::string s1 = SSTR( i );
int x = 23;
std::string s2 = SSTR( "i: " << i << ", x: " << x );
return 0;
}
You can use this function to convert int to std::string after including <sstream>:
#include <sstream>
string IntToString (int a)
{
stringstream temp;
temp<<a;
return temp.str();
}
You might include the implementation of itoa in your project.
Here's itoa modified to work with std::string: http://www.strudel.org.uk/itoa/
Suppose I have integer = 0123456789101112. Now, this integer can be converted into a string by the stringstream class.
Here is the code in C++:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n,i;
string s;
stringstream st;
for(i=0;i<=12;i++)
{
st<<i;
}
s=st.str();
cout<<s<<endl;
return 0;
}
#include <string>
#include <stdlib.h>
Here, is another easy way to convert int to string
int n = random(65,90);
std::string str1=(__String::createWithFormat("%c",n)->getCString());
you may visit this link for more methods
https://www.geeksforgeeks.org/what-is-the-best-way-in-c-to-convert-a-number-to-a-string/
Like this function in C:
size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );
I've looked in C++ file stream and found this one:
ostream& write ( const char* s , streamsize n );
this one only accepts char* instead of void*
but does it really matter if I use a C-style fwrite function in c++?
Streams are probably what you're looking for unless I misunderstand your question. There are many flavors that handle different jobs, like outputting to a file:
#include <cstdlib>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream f("c:\\out.txt");
const char foo[] = "foo";
string bar = "bar";
int answer = 42;
f << foo << bar<< answer;
return 0;
}
...building strings like you would with printf:
#include <cstdlib>
#include <sstream>
#include <string>
#include <iostream>
using namespace std;
int main()
{
stringstream ss;
const char foo[] = "foo";
string bar = "bar";
int answer = 42;
ss << foo << bar<< answer;
string my_out = ss.str();
return 0;
}
...and they can even handle your own types, if you tell them how:
#include <cstdlib>
#include <string>
#include <iostream>
using namespace std;
class MyGizmo
{
public:
string bar_;
int answer_;
MyGizmo() : bar_("my_bar"), answer_(43) {};
};
ostream& operator<<(ostream& os, const MyGizmo& g)
{
os << g.bar_ << " = " << g.answer_;
return os;
}
int main()
{
MyGizmo gizmo;
cout << gizmo;
return 0;
}
You can use either one. Using char * instead of void * doesn't make much real difference -- both fwrite and ostream::write are typically used for a variety of data types (with with C++, you need to add an explicit cast to char *, where in C the cast will happen implicitly, assuming you've included a proper prototype for fwrite).
In C++ you will want to use std::ofstream objects to write to a file. They can accept any type of data using the << operator, in much the same way that std::cout works for writing to the console. Of course, just like std::cout, if you want to print a custom type, you will need to define an operator<< overload for it.
An example:
std::ofstream outfile("myfile.txt");
int i = 5;
double d = 3.1415926535898;
std::string s = "Hello, World!";
outfile << i << std::endl;
outfile << d << std::endl;
outfile << s << std::endl;
To use std::ofstream, you need to #include <fstream>.
The outfile object will automatically close the file when it destructs, or you can call its close() method.
Contrary to already given answers, there is an important difference between fwrite() and ostream::write().
fwrite() writes binary data unmodified (well, on those poor non-Unix platforms there is endline translation, unless the file is opened in binary mode).
ostream::write() uses locale to transform every character, this is why it accepts char* rather than void*. Normally, it uses the default "C" locale, which does not do any transformation.
Just keep in mind that basic_ostream is a formatter on top of basic_streambuf, not a binary sink.
I'm developping in C++, using the Qt framework.
I need to convert a long double value into a string (ideally a QString, but could be something else).
So far, I always used QString::number() for numerical->string conversion, but there is no overloading for the long doubletype.
Thanks
Simple:
string convert(long double myLongDouble) {
stringstream blah;
blah << myLongDouble;
return blah.str();
}
With Templates:
template<class T> string convert(T _input) {
stringstream blah;
blah << _input;
return blah.str();
}
QString has a static function to construct a QString from a std::string, so wheaties' answer could be rewritten as:
#include <sstream>
#include <QString>
...
QString qStringFromLongDouble(const long double myLongDouble)
{
std::stringstream ss;
ss << myLongDouble;
return QString::fromStdString(ss.str());
}
Boost has lexical_cast for this purpose. It pretty much wraps the solution wheaties gave into a class template.
The answer marked is not complete, it will save it with only 6 decimal digits.
It should be like this:
#include <sstream>
#include <iomanip>
#include <limits>
QString longDoubleToString(long double value)
{
std::stringstream stream;
stream << std::fixed << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << value;
return QString::fromStdString(stream.str());
}