Public Group

# 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.

## 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!>

##### Share on other sites
We're going to need a little more detail about the environment you're working in. Is it a console, a GUI, a text file?

##### Share on other sites
Sorry yes it's a console app :S

##### Share on other sites
There is no reliable, standard, portable way to do this in c++.

##### Share on other sites
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 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 on other sites
Hidden
Sorry this is kinda confusing me

But I will work at it for a bit thanks!

Hidden
If I don't get it I'm going to just

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

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 on other sites
If you use std::string to hold your character strings, then you can call the size() member function on a string to find out how long it is.

1. 1
2. 2
Rutin
19
3. 3
4. 4
5. 5

• 13
• 26
• 10
• 11
• 9
• ### Forum Statistics

• Total Topics
633736
• Total Posts
3013598
×