Archived

This topic is now archived and is closed to further replies.

Andre the Giant

Dumb questionn

Recommended Posts

Is there an ''excepted'' way to convert a number to a string? for example, this code does not do what I want it to: string s[10]; for (int i = 1; i < 10; i++){ s = "number " + i; } instead of making the s array like this: number 1 number 2 number 3 ... It does something wierd like this: umber mber ber (Im not sure thats exactly what happens, but something similar - im at work right now and cant remember exactly) I know I could use the itoa() function, but people discourage the use of that function and i dont know why. Also, I know of the sprintf() function which is ugly but also works. I want to know what other people do when the need to do such things? Its not my fault I''''m the biggest and the strongest; I don''''t even exercise.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Well, a string is really a pointer. So when you say "number" + 1, you are really saying, take the address pointing to the string "number" and offset it by 1. So you get "umber". Then it increments again and you get offset by 2, "mber", etc. What you want is to append the string equivilent of the number to the end of the string "number". I think with the string class you can just use the stream operator << to append it. Try something like this:

string s[10];
for (int i = 1; i < 10; i++){
s = "number " << i;
}

Share this post


Link to post
Share on other sites