Jump to content
  • Advertisement
Sign in to follow this  
MrGuild

C++ center command

This topic is 2528 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

How can I center my text in C++ in the least amount of code without having to make a function?

Thanks for the help if possible!> :D

Share this post


Link to post
Share on other sites
Advertisement
What do you mean? Can't I just simply somehow put my text in the center of the console application? Even if I need to create a function thats alright.

Share this post


Link to post
Share on other sites
Hmm, I wish I used the console for a little more than debugging XD Anyhow, the text in a console is usually monospaced (at least I haven't come by one that wasn't), which means each character is the exact size as the other ones. If you can figure out how many characters will fit into a line in the console, you can do:


// suppose totalChars is the total amount of characters per line in a console
// and str contains the string you want to output.
std::cout << std::string( (totalChars-str.size())/2, ' ' ) << str << std::endl;


Basically what happens is: you take the total chars you have, take away whatever space the string will occupy, and then divide it in half. This represents how many spaces you have to insert so that your string is centered. I also can't say that creating an std::string variable just to add blank spaces is a good idea.

Unfortunately, I'm not aware of any standard way to find out how many characters you can fit into the console. If I'm correct, the Windows console always has the same size (even if you maximize) but Linux consoles can be of variable size, and usually are.

Share this post


Link to post
Share on other sites
Hidden
If I don't get it I'm going to just


char Space;
Space = ' ';
cout << Space << Space << "Some Text" << endl;

Share this post


Link to post
I have:


int totalChars;
totalChars = 25;
const char* str;
str = "Testing";
std::cout << std::string( (totalChars-str.size())/2, ' ' ) << str << std::endl;
return 0;


but it requests 'size' int 'str' I was wondering what that even was?


std::cout << std::string( (totalChars-str.size())/2, ' ' ) << str << std::endl;

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!