So I'm learning some stuff in College on C++, and the teacher and I got into a discussion on how to actually center text to the output screen. So my suggestion was to use setw
but get the length of the string and the size
of the console screen, do the algorithm and BAM we have truly centered text. He says the screen size is 80
but the screen can be resized, which doesn't work no matter what if the output is centered the the user starts resizing. Just a minor question I have, how to get the actual size of the console screen?
#include <iostream>
#include <string>
using namespace std;
const int SCR_SIZE = 80;//some way of telling size
int main(){
string randomText = "Hello User!";
cout << setw( ( (80 / 2) + (randomText.length() / 2 ) ) )
<< randomText
<< endl;
return 0;
}
Searched a little and found this bit
#include <cstdlib>
system("MODE CON COLS=25 LINES=22");
Would that work to set it on execution to make sure my size is what I want it to be? Just read through it so I'm not 100% positive if that in fact is a c++ library
You can #include <windows.h>
and call GetConsoleScreenBufferInfo
. To use this, you'll need a Windows handle to your standard output stream, which you can retrieve with GetStdHandle
.
Be aware that the resulting code will be Windows-specific (whereas your current code is portable, so it should run fine on Linux, Mac OS, *BSD, etc.)