String Insert variable argument

Feb 19, 2011 at 8:53pm
I'm trying to center a title string on a 80 character wide console. The idea is to have a user input the title, then the system figures out how long the title is and centers it on the screen.

My attempt fails when I place an int variable into the string's insert member function's argument:

1
2
3
string title = "TEST TITLE"; //normally input by user, static for example
int titleBuffer = ((80 - title.size()) / 2); //determines amount of buffer space on either side of title in console
gameTitle = title.insert(0, titleBuffer, ' '); //places buffer amount in front of title to effectively center it 


However, if I replace the variable with it's actual value, then it works fine. Any ideas how to make it work with the int variable? I tried using a reference as well with no luck.

This works when variable is replaced by value:

1
2
3
string title = "TEST TITLE";
int titleBuffer = ((80 - title.size()) / 2);
gameTitle = title.insert(0, 35, ' ');


I can also make this solution work by iterating through the string and add the buffer there but was hoping to get the insert to work instead. Maybe there is a better way altogether?

Thanks,

Steve
Last edited on Feb 19, 2011 at 9:39pm
Feb 19, 2011 at 9:21pm
Your calculation is wrong. It should be: ((80 / 2) - (title.size() / 2))
Feb 19, 2011 at 9:56pm
In my application if a string is odd sized, I prefer the additional space to be after the string, not in front of it. However, your calculation would place the extra space before the string. There is no right or wrong calculation here, it's a matter of designer's preference, but I appreciate the feedback.

Getting back to the original question, can a variable be used in a member function's numerical argument?
Last edited on Feb 19, 2011 at 10:00pm
Feb 19, 2011 at 9:59pm
I actually got this to work, I had a different error going on.
Topic archived. No new replies allowed.