simple string management

G

gurumare

hello, i would like to increment a string in a for loop. The desired
output would look like:

team0
team1
team2

and so on. I use the code

for (int i = 0; i < numTeams; i++) {
sName = "team"+i;
a.SetName(sName);
}

and get the output:

team
eam
am

and so on. What can i do to get the desired effect in the most simple
way possible? thank you
 
L

Lionel

hello, i would like to increment a string in a for loop. The desired
output would look like:

team0
team1
team2

and so on. I use the code

for (int i = 0; i < numTeams; i++) {
sName = "team"+i;
a.SetName(sName);
}

and get the output:

team
eam
am


Amusing. What I believe you are doing is getting a memory address from
"team" and then you are adding a unit of i byte(s) to that memory
address with the +i. In C++ you can't use the + operator for string
manipulation. From the best of my knowledge you will need to convert the
integer i to an ascii then append it to the string using something like
strcat which can be found at:

http://www.cplusplus.com/ref/cstring/

Of course if you use google you will find all this information very easily.
 
B

Bart

hello, i would like to increment a string in a for loop. The desired
output would look like:

team0
team1
team2

and so on. I use the code

for (int i = 0; i < numTeams; i++) {
sName = "team"+i;
a.SetName(sName);
}

and get the output:

team
eam
am

and so on. What can i do to get the desired effect in the most simple
way possible? thank you


The simplest possible way, assuming sName is a std::string, is:

sName = "team";
sName += "0123";

But this has limited use and of course you have to be careful not to
overrun the string literal. The best solution is to use
std::stringstream as was already suggested.
 
B

Ben Pope

hello, i would like to increment a string

I think you should ask yourself what you actually mean here.
> in a for loop. The desired
output would look like:

team0
team1
team2

and so on.

OK, so do you want to:

a) Increment the ASCII code of the last character of the string, starting at '0'.

b) Increment the integer value of the last bit of the string, assuming it to be of base x, and starting at 0.

c) Append to a string, a string representation of a number, which is of base x, starting at 0, which you are able to increment, in a loop.

I would guess that you mean option c, in which case the implementation should be a bit more obvious, when expressed in that way.

Also, do you have any bounds on these numbers? What happens at these bounds?

Ben
 

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,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top