Original Post
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!>
Thanks for the help if possible!>
// 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;
int totalChars;
totalChars = 25;
const char* str;
str = "Testing";
std::cout << std::string( (totalChars-str.size())/2, ' ' ) << str << std::endl;
return 0;
std::cout << std::string( (totalChars-str.size())/2, ' ' ) << str << std::endl;
std::string str = "Testing";
std::cout << std::setw( (screenWidth + str.length()) / 2) << std::right << str;
What do you mean? Can't I just simply somehow put my text in the center of the console application?
[/quote]
The point being made is that standard, portable C++ does not make any assumptions about the nature of the standard output streams. They may not be consoles. They could also be files, sockets, printers, IPC devices such as pipes, the bit bucket or something more esoteric again. Not all of these have the concept of a fixed width which you could use to calculate a "center" from.
For instance, you can make std::cout a file in your program (shown here as foo.exe), by running it from cmd.exe like so:
C:\path\to\executable> foo.exe > output.txt
You can make std::cin a file using < input.txt too. It is also possible to redirect std::cerr, using 2>.
Running the entire program non-interactively and logging all output to standard streams could be done like so:
C:\path\to\executable> foo.exe < input.txt > output.txt 2> error.txt
Just FYI, you can also merge stdout and stderr output by using the following:
C:\path\to\executable> foo.exe > output.txt 2>&1
It is also possible to set up pipes to other processes, and that other program might print the data, send it across the network or do any number of things with it.
These interesting tricks aside, the proper solution is to use a console/terminal library, like ncurses.
However, as a beginner, assuming a fixed width console isn't all that bad, and you would be right in ignoring the "proper solution" for the time being and concentrating on learning the core language skills you will need.
const char* str;
str = "Testing";
std::cout << std::string( (totalChars-str.size())/2, ' ' ) << str << std::endl;
std::string str = "Test string.";
std::cout << std::setw ( (screenWidth - str.size()) / 2 ) << std::right << std::str;
This topic has been locked by a moderator. New replies are not allowed.
With your permission, GameDev.net uses analytics cookies to understand how people use the platform. You can accept analytics or continue with necessary cookies only. Learn more