Discussion:
const char *
(too old to reply)
Chunekit Pong
2009-08-24 00:59:43 UTC
Permalink
how can I concatenate an integer into a string?

the following does not work

Create function takes a (const char *)

==============
for ( int i = 0; i < 8; i++) {
m_Piano[i].Create("image" + i + ".png");
}
Nathan Mates
2009-08-24 01:09:58 UTC
Permalink
Post by Chunekit Pong
how can I concatenate an integer into a string?
If you're using char* for strings -- which is far more C-style
strings than the C++ code you showed -- then you should become good
friends with the printf family of functions, especially sprintf. Go
consult your language documentation or textbook for more details.
Hint: %d is your friend here.

Nathan Mates
--
<*> Nathan Mates - personal webpage http://www.visi.com/~nathan/
# Programmer at Pandemic Studios -- http://www.pandemicstudios.com/
# NOT speaking for Pandemic Studios. "Care not what the neighbors
# think. What are the facts, and to how many decimal places?" -R.A. Heinlein
xiaosi
2009-08-24 07:07:13 UTC
Permalink
#include <stdio.h> //_snprintf
char sz[16];
for ( int i = 0; i < 8; i++) {
_snprintf(sz, sizeof(sz), "image%d.png", i);
m_Piano[i].Create(sz);
}

-or-
char sz[] = "imageX.png";
for ( int i = 0; i < 8; i++) { //i must < 10
sz[sizeof("image")-1] = i + '0';
m_Piano[i].Create(sz);
}
Post by Chunekit Pong
how can I concatenate an integer into a string?
the following does not work
Create function takes a (const char *)
==============
for ( int i = 0; i < 8; i++) {
m_Piano[i].Create("image" + i + ".png");
}
Ulrich Eckhardt
2009-08-24 07:08:51 UTC
Permalink
Post by Chunekit Pong
how can I concatenate an integer into a string?
Two steps:
1. Convert the integer to a string.
2. Concatenate the strings.

Using those as basics, you should be able to easily find information with a
websearch. BTW: I agree that it would be more C++ish to use 'std::string'
instead of 'char const*', even if you can't change the parameter there is
still the 'c_str()' memberfunction. For formatting, 'std::stringstream' is
a good start then.

Uli
--
C++ FAQ: http://parashift.com/c++-faq-lite

Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932
Continue reading on narkive:
Loading...