Add an integer to a string without using std::stringstream

  • Thread starter Christopher Benson-Manica
  • Start date
C

Christopher Benson-Manica

If std::stringstreams are unavailable, how would you go about adding
an integer (or unsigned integer) to a string?
 
J

John Harrison

Christopher Benson-Manica said:
If std::stringstreams are unavailable, how would you go about adding
an integer (or unsigned integer) to a string?

sprintf the integer to a C string and then append that C string to the C++
string. That would probably be the way I would do it in any case.

John
 
M

Mike Wahler

Christopher Benson-Manica said:
If std::stringstreams are unavailable, how would you go about adding
an integer (or unsigned integer) to a string?

#include <cstdio>
#include <iostream>
#include <limits>
#include <string>

int main()
{
std::string s("Hello");
int i(42);
char *tmp = new char[std::numeric_limits<int>::digits10 + 2];
std::sprintf(tmp, "%d", i);
s += tmp;
std::cout << s << '\n'; /* prints "Hello42"
delete[] tmp;
return 0;
}

-Mike
 
S

Siemel Naran

Christopher Benson-Manica said:
If std::stringstreams are unavailable, how would you go about adding
an integer (or unsigned integer) to a string?

In addition to sprintf as others point out, there is also istrstream -- need
to #include <strstream.h>. Not sure if it is deprecated or even still part
of the standard, but imagine it is fine.
 
B

Buster

Christopher said:
If std::stringstreams are unavailable, how would you go about adding
an integer (or unsigned integer) to a string?

#include <limits>
#include <string>
#define X *--o='0'+(x%10);x/=10;
#define O while(x){*--o=',';X if(x)X if(x)X}

template <typename Integer>
void append_int (Integer x, std::string & s)
{
char buffer [std::numeric_limits <Integer>::digits10 * 4 / 3 + 2];
char * o = buffer + sizeof buffer;

if(x<0){if((x=-(x+1))%10-9){*--o='1'+(x%10);x/=10;}
else{*--o='0';x/=10;++x;}X if(x)X O*--o='-';}
else if(x){X if(x)X if(x)X O}else{*--o='0';}

s.append (o, buffer + sizeof buffer);
}
 
M

Michiel Salters

Siemel Naran said:
In addition to sprintf as others point out, there is also istrstream -- need
to #include <strstream.h>. Not sure if it is deprecated or even still part
of the standard, but imagine it is fine.

std::[io]strstream, in <strstream>, is standard but deprecated.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top