Concatenating Multiple char* s (unsolved)

I have the following code:
1
2
3
4
5
6
7
    char* attacks;
    attacks="Choose an attack!\n\n";
    for(i=1;i<=ini.ReadInteger("config","number",0);i++)
    {
    attacks=attacks+(char*)"("+(char*)i+(char*)") "+ini.ReadString((char*)i,(char*)"text",(const char*)"No Text Specified");
    }
    cout<<attacks<<endl;


And of course I get the error:

invalid operands of types `char*' and `char*' to binary `operator+'

Because I can't concatenate multiple char* s with a plus sign.

How would I be able to concatenate multiple char* s? I can't use strcat because it only accepts two arguments, and I don't want to nest strcat s.

Thanks!
Last edited on
char*s are not strings. This is a very common misconception.

You also can't cast an integer to a char* in order to make a formatted string. (char*)i does not print the integer in string form, even though it may compile.

Use std::string and/or std::stringstream for this. There are ways to do with with C style strings, but they're more complicated and more errorprone.

I hope my syntax here is right -- I don't often use stringstream, so I might be off (code might not be copy/pasteable) but you should be able to get the idea:

1
2
3
4
5
6
7
8
9
10
11
std::stringstream attacks;
attacks << "Choose an attack!\n\n";
for( ... )
{
  std::stringstream istr;
  istr << i;   // format 'i' to be a string

  attacks << '(' << i << ')' << ini.ReadString( istr.str().c_str(),"text","No Text Specified");
}

cout << attacks.str() << endl;
That doesn't work. I get

aggregate `std::stringstream attacks' has incomplete type and cannot be defined

aggregate `std::stringstream istr' has incomplete type and cannot be defined


EDIT:
I added #include <sstream>.
However, It just outputs me the memory location. (0x23FCA4)

EDIT2:
I want it to be a char*. I know they aren't strings, I just like them and are used to them.
Last edited on
well you can't be that used to them if you can't do stuff like this with them =P

anyway I'll pre-empt another error here:

char* attacks = "Choose an attack!\n\n";

no good. this will crash or do other bad things if you try to append to this string because you have no buffer, you're just pointing to a static string.

Better:

char attacks[100] = "Choose an attack!\n\n";

But beware that this will still crash if you exceed 100 (or really 99 because there's a null terminator) characters with your string appending. So be sure your buffer is large enough.
What are you trying to do? Are you trying to set the world record for the longest line of incomprehensible code? You must not be very "used to" char* because what you are trying to do simply isn't possible with a char*. In fact it would be difficult to accomplish this task with std::string with one line of code. You are going to have to write more lines of code within the for loop, regardless of whether you wish to use char* or std::string.
Topic archived. No new replies allowed.