adding an integer to an stl string

E

exits funnel

Hello,

I'm trying to append the ascii representation of an integer to an stl
string and I'm having some trouble. I've got the following bits of code:

#include <string>
#include <cstdlib>

....

char buf[10];
itoa(14, buf, 10);
string m_name = "House #" + buf;

When I try to compile this, my compiler complains about 'itoa' being an
undeclared function and in fact grepping stdlib.h verifies that the
funcion is not to be found. I've been away from c for some time and am
now trying to learn c++. Two questions then:

1) Where can I find atoi or some equivalent function?
2) Is there an easier way to add an integer to the string?

Thanks in advance for any replies!

-exits
 
M

Mike Wahler

exits funnel said:
Hello,

I'm trying to append the ascii representation of an integer to an stl
string and I'm having some trouble. I've got the following bits of code:

#include <string>
#include <cstdlib>

...

char buf[10];
itoa(14, buf, 10);

There is no such function as 'itoa()' in standard C++.
string m_name = "House #" + buf;

Undefined behavior. The array 'buf' was never initialized.
When I try to compile this, my compiler complains about 'itoa' being an
undeclared function and in fact grepping stdlib.h verifies that the
funcion is not to be found.

Right, it's not part of C++.
I've been away from c for some time and am
now trying to learn c++. Two questions then:

1) Where can I find atoi or some equivalent function?

The standard function 'atoi()' is declared by standard header
<stdlib.h> or <cstdlib>. But note that this function will not
do what you're asking about.

2) Is there an easier way to add an integer to the string?

Yes, use a stringstream. See below.
Thanks in advance for any replies!

-exits

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

int main()
{
std::string s("Hello");
int i(42);
std::eek:stringstream oss;
oss << s << i;
std::string output(oss.str());
std::cout << output << '\n'; /* prints Hello42 */
return 0;
}

-Mike
 
E

exits funnel

#include said:
#include <sstream>
#include <string>

int main()
{
std::string s("Hello");
int i(42);
std::eek:stringstream oss;
oss << s << i;
std::string output(oss.str());
std::cout << output << '\n'; /* prints Hello42 */
return 0;
}

-Mike

Thanks Mike, this is exactly what I was looking for.

-exits
 

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

Forum statistics

Threads
473,763
Messages
2,569,563
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top