Converting an int to std::string - c++

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/

Related

std::string::insert doesn't work with to_string(). CPP

I am writing a code to insert an integer at an index of the string, but after providing the integer to add as string, insert function is not giving the correct output.
It is giving the error that :
no matching member function to call for insert string
This is my code:
#include <iostream>
using namespace std;
int main()
{
string s = "45564528";
int x = 8;
s.insert(s.begin()+5,to_string(x));
cout<<s<<endl;
return 0;
}
The expected output is 455648528.
Looking at the documentation for std::string::insert() shows that it takes a char or an iterator range, not a std::string, which std::to_string() naturally returns. At least, this is the case for the overloads that take an iterator for the first argument.
#include <iostream>
#include <string> // CHANGED: Include what you use
// using namespace std; // CHANGED: Bad practice
int main()
{
std::string s = "45564528";
int x = 8;
// CHANGED: Create string from the int, and use the iterator range overload
// to account for multi-digit numbers
auto tmp = std::to_string(x);
s.insert(s.begin()+5, tmp.begin(), tmp.end());
std::cout << s << '\n'; // CHANGED: std::endl is rarely actually needed
return 0;
}
There is an overload that lets you insert another std::string, but the first argument must be an index and not an iterator. So this would work as well:
#include <iostream>
#include <string>
int main()
{
std::string s = "45564528";
int x = 8;
s.insert(5, std::to_string(x));
std::cout << s << '\n';
return 0;
}

Trying to convert a string into a int using stringstream

I'm trying check if a string representation equals given integer. I'm meant to use stringstream for this in a function. I also have an operator= for this as well.
I'm a little confused on how to execute these together and if I'm missing something. This is the last bit to an assignment I have, this is just a small snippet of my whole program. I can't find many guides on this, and I sense they all direct me to atoi or atod, which I'm not allowed to use.
#ifndef INTEGER
#define INTEGER
using std::string;
class Integer
{
private:
int intOne;
string strOne;
public:
Integer() {
intOne = 0;
}
Integer(int y) {
intOne = y;
}
Integer(string x) {
strOne = x;
}
void equals(string a);
Integer &operator=(const string*);
string toString();
};
#endif
In this header I'm not sure what argument I'm to use for the = operator.
#include <iostream>
#include <sstream>
#include <string>
#include "Integer.h"
using namespace std;
Integer &Integer::operator=(const string*)
{
this->equals(strOne);
return *this;
}
void Integer::equals(string a)
{
strOne = a;
toString(strOne);
}
string Integer::toString()
{
stringstream ss;
ss << intOne;
return ss.str();
}
#include <iostream>
#include <cstdlib>
#include <conio.h>
#include <string>
#include <ostream>
using namespace std;
#include "Menu.h"
#include "Integer.h"
#include "Double.h"
int main()
{
Integer i1;
i1.equals("33");
cout << i1;
}
Sorry if its a bad question I'm not too familiar with this type of assignment and will take any help I can get. Thanks.
you can use std::to_strig() that lets you convert from int to a string that represents the same number.
So if i understand correctly, you want to overload operator =, and that is a bad idea, since operator= is used for assignment not for comparison.
The correct operator signature is:
ReturnType operator==(const TypeOne first, const TypeSecond second) [const] // if outside of class
ReturnType operator==(const TypeSecond second) [const] // if inside class
Since you can't compare string to integer (they are different types), you need to write your comparisment function, since you don't have one i will write one for you:
bool is_int_equal_string(std::string str, int i)
{
std::string tmp;
tmp << i;
return tmp.str() == i;
}
Last but not least, you need to merge both of those, into one convenient operator:
// inside your Integer class
bool operator==(std::string value) const
{
std::stringstream tmp;
tmp << intOne;
return tmp.str() == ref;
}
Now you can use this operator, just like any other:
Integer foo = 31;
if (foo == "31")
cout << "Is equal" << endl;
else
cout << "Is NOT equal" << endl;
I hope this helps.
If you are allowed to use std::to_string then it would be the best.
Otherwise, you could create a function to handle the equality between the string and the integer with the use of std::stringstream:
Example:
bool Integer::equal(const string& str)
{
stringstream ss(str);
int str_to_int = 0;
ss >> str_to_int;
if (intOne == str_to_int)
return true;
else
return false;
}
Combine this with an if statement:
int main()
{
Integer i{100};
if (i.equal("100"))
cout << "true" << endl;
else
cout << "false" << endl;
}

Data Type Convert

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;
}

Is there a C++ way to write file with any type of data?

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.

long double to string

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());
}