std::string, Append a number

J

JKop

The following isn't doing what I thought it would do:

#include <iostream>

int main()
{
int k = 56;

std::string blah(" ");

blah += k;

std::cout << "\n\n" << blah << "\n\n";
}



How do I simply append a number to an std::string?


As in:

"Amount: "

becoming

Amount: 56"

?

Thanks,

-JKop
 
S

Sumit Rajan

JKop said:
The following isn't doing what I thought it would do:

#include <iostream>

int main()
{
int k = 56;

std::string blah(" ");

blah += k;

std::cout << "\n\n" << blah << "\n\n";
}



How do I simply append a number to an std::string?


As in:

"Amount: "

becoming

Amount: 56"


You could try something like this:

#include <string>
#include <iostream>
#include <sstream>

int main()
{
std::string s("Amount:");
int tot = 42;
std::eek:stringstream oss;
oss << s << ' ' << tot << '\n';
std::cout << oss.str();
}

Regards,
Sumit.
 
A

Andre Kostur

You could try something like this:

#include <string>
#include <iostream>
#include <sstream>

int main()
{
std::string s("Amount:");
int tot = 42;
std::eek:stringstream oss;
oss << s << ' ' << tot << '\n';
std::cout << oss.str();
}

... or look up the lexical_cast<> item in Boost (http://www.boost.org)...
(which I think does the same thing :) )
 
Z

Zian Smith

JKop said:
The following isn't doing what I thought it would do:

#include <iostream>

int main()
{
int k = 56;

std::string blah(" ");

blah += k;

std::cout << "\n\n" << blah << "\n\n";
}



How do I simply append a number to an std::string?


As in:

"Amount: "

becoming

Amount: 56"

?

Thanks,

-JKop

Use ostringstream to convert the int to a string type:


main()
{
int k=56;
std::string blah("woot ");

std::eek:stringstream os;
os << k;
std::string k_str = os.str(); //retrieve as a string

blah += k_str;
std::cout << blah << "\n\n";
}
 
M

Matt Hurd

Andre Kostur said:
.. or look up the lexical_cast<> item in Boost (http://www.boost.org)...
(which I think does the same thing :) )

Yes, boost::lexical_cast is nicer, it hides the stream usage.

Specific reference here: http://www.boost.org/libs/conversion/lexical_cast.htm

This is the code, FYI, using your example.

#include <iostream>
#include <boost/lexical_cast.hpp>

int main()
{
int k = 56;

std::string blah(" ");

blah += boost::lexical_cast<std::string>(k);

std::cout << "\n\n" << blah << "\n\n";
}

Regards,

Matt Hurd
www.hurd.com.au
 

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,995
Messages
2,570,236
Members
46,825
Latest member
VernonQuy6

Latest Threads

Top