Centering txt output issue

Hi,

I'm having a problem centering variable data thats being printed to the screen. Since the text im using is different from the variables.


Now i have a function that centers strings. But when i try to print out a variable on the right side of the string it centers the string and the variable stays to the right of it, and if i try to pad the string to make it move more to the left it doesn't move the string to the left and only makes the variable information shift to the right.

(centered string) (Variable Printed)
With Padding
(centered string)-------------------->(Variable Printed)

When I want the whole group moved left with no big space in between.

1
2
3
4
5
6
7
8
9
10
11
12
void centerstring(char*s)  
{  
	HANDLE hOut;
	hOut = GetStdHandle(STD_OUTPUT_HANDLE);
	COORD NewSBSize;
	NewSBSize = GetLargestConsoleWindowSize(hOut);
	int l=strlen(s);
	int pos=(int)((NewSBSize.X-l)/2);
	for(int i=0;i<pos;i++)
	cout<<" ";
	cout<<s;
} 





1
2
centerstring("Registered To: "); cout << RegisteredToName; cout << "\n";
centerstring("Account Type : "); cout << RegisteredType; cout << "\n";




Essentially what i want is a Left Aligned Centered

I want text centered. Then the text to all be in a straight line on the left side of that center.




[---------------TEXT HERE---------------]
[----------BIGGER TEXT HERE----------]

Like this:

[---------------TEXT HERE---------------]
[---------------BIGGER TEXT HERE-----]


And to be able to control the padding without messing up the variable print.
Last edited on
See the IO manipulators std::setw, std::left and std::right. For some reason a std:: center doesn't exist so you would need to use your own logic to output centered text.

http://www.cplusplus.com/reference/iostream/manipulators/

Funny. I was asking myself this very question just today.
well the setw isn't going to work the whole point of this is so i don't have to pad each output individually not to mention im using a script to open the console window to the users max screen size. So the centering position is going to be different depending on the screen size... now ive got plans on screen size needing to be at least 21" to play the game im working on. So i have a minimum point of reference in terms of the max size i can have to work with space wise and still fit inside a 21" screen.



on a final note


They really should make a std::center std:leftcenter and std::rightcenter
Last edited on
closed account (zwA4jE8b)
whos they.. you can make it.

Probably somethinglike...
Get the current width of the console in characters
get the string/data to be centered.

center of console = size / 2
start position of text = center of console - (text / 2)
whos they.. you can make it.

Probably somethinglike...
Get the current width of the console in characters
get the string/data to be centered.

center of console = size / 2
start position of text = center of console - (text / 2)



Already have exactly that

1
2
3
4
5
6
7
8
9
10
11
12
void centerstring(char*s)  
{  
	HANDLE hOut;
	hOut = GetStdHandle(STD_OUTPUT_HANDLE);
	COORD NewSBSize;
	NewSBSize = GetLargestConsoleWindowSize(hOut);
	int l=strlen(s);
	int pos=(int)((NewSBSize.X-l)/2);
	for(int i=0;i<pos;i++)
	cout<<" ";
	cout<<
}



What i need is to align the text to the left of center.
Last edited on
It is easy. :-(

1
2
int consoleWidth = 80; //Or get the value through your favorite function.
cout << setw(consoleWidth / 2) << " " << "This shows to the left of the center." << endl;


It is just basic math.
Again that just centers the text. I want it centered and then the text aligned to the left part of the center.... have any of you ever used MSWord?



This is what it would look like:

Centered

[---------------TEXT HERE---------------]
[----------BIGGER TEXT HERE----------]

Centered And Aligned Left

[---------------TEXT HERE---------------]
[---------------BIGGER TEXT HERE-----]


int pos=(int)((NewSBSize.X-l)/2);
Last edited on
Know how to apply a percentage? (That is what you do with 'center'; you apply 50%)

Left position = (width of screen - width of text) * percentage

Hope this helps.
I got the math part. But the part thats getting me is how to do it with printed variables... for example:


1
2
3
4
5
6
int Number = 0;
string Name = "SomeName";


cout << Number;
cout << SomeName;
That is because you are skipping the math part.
How are you to know your total field widths if you don't know the width of your output?

If you want to do something simple, like just output N spaces before everything, that can be done also:

 
cout << string( 30, ' ' ) << "Value of X: " << x << "\n";
The real problem will be things like inventory display, bank display, equipment display etc because the lengths of the strings and other information will be different and at different times. And wouldn't what your suggesting be exactly what im doing except im doing it like this:

centerstring("Some text here <whitespaced> \n");

or another variation depending on which way i want to shift it.


centerstring(" <whitespaced> Some text here\n");


If you want to move right you whitespace on the left 2 for every 1 space you want it moved left and opposite for right.



There is 2 problems:

#1 I don't always know what the output/input will be.
#2 The centering via centerstring doesn't work with variable output, only typed in strings like above.



The 2 main things i want.


To be able to center and left align my text where wanted... Particularly menus. And to be able to center/align printed variables with some kind of calculation that figures out the length of the variable before its printed and automatically aligns it.




If someone can figure this out, please give me a full working example. I learn by example by seeing the full code and figuring out how the different parts work. Deconstruct it and use it in future programs. Thanks
Last edited on
You are asking a question then lecturing me about the answer?

I'm telling you right now that the only way you'll get it is by working it through instead of pretending you already know all the answers.

Want an example? Fine.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
#include <limits>
#include <sstream>
#include <string>
#include <vector>

#include <windows.h>
#ifdef max
#undef max
#endif

using namespace std;

int main()
  {
  HANDLE                     hstdout;
  CONSOLE_SCREEN_BUFFER_INFO csbi;

  hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
  GetConsoleScreenBufferInfo( hstdout, &csbi );

  // This is the actual visible width of your console window in characters
  size_t width = csbi.srWindow.Right - csbi.srWindow.Left;

  // Get all the inputs (user may input any length string, of course)
  string inputs[ 3 ];
  double number;

  cout << "Enter foo: ";  getline( cin, inputs[ 0 ] );
  cout << "Enter bar: ";  getline( cin, inputs[ 1 ] );
  cout << "Enter quux: "; getline( cin, inputs[ 2 ] );
  cout << "Enter a number: "; cin >> number; cin.ignore( numeric_limits <streamsize> ::max(), '\n' );

  // Generate our list of things to output
  vector <string> outputs;
  outputs.push_back( string( "Foozle Item X:          " ) + inputs[ 0 ] );
  outputs.push_back( string( "How low can you go bar: " ) + inputs[ 1 ] );
  outputs.push_back( string( "Quuxified:              " ) + inputs[ 2 ] );
  {
    ostringstream oss;
    oss <<                   "A numeric value:        " << number;
    outputs.push_back( oss.str() );
  }

  // Make sure that no output is too wide
  for (size_t n = 0; n < outputs.size(); n++)
    if (outputs[ n ].length() > (width - 1))
      outputs[ n ].erase( width - 1 );

  // Calculate the width of the largest output item
  size_t output_width = 0;
  for (size_t n = 0; n < outputs.size(); n++)
    output_width = max( outputs[ n ].length(), output_width );

  // Calculate our indent
  string indent( (width - output_width) / 2, ' ' );

  // Draw all the items
  for (size_t n = 0; n < outputs.size(); n++)
    cout << indent << outputs[ n ] << endl;

  outputs.clear();
  cout << string( 4, '\n' ) << "All done.\n";
  return 0;
  }

Everything you need to know is in there.
1. If you want stuff lined up neatly, then you have to know more than one line of output's length.
2. Otherwise, just apply the centering algorithm (the math) to each line as it comes.
3. You have to know the length of the output before you output it to center it. (This means you have to make things like numbers into a string first!)
4. You must make sure that your outputs fit into the maximum allotted space.

I often find it helpful to get out a piece of graphing paper and draw what I want to see -- then I can calculate borders and margins etc before I write my code. (And I've done this kind of thing so often that I will usually make my output routines work in a very modular way, so that I can change one thing, like a margin, without having to rewrite the entire code.)

Good luck.
I often find it helpful to get out a piece of graphing paper and draw what I want to see -- then I can calculate borders and margins etc before I write my code.
Just dropping by to say that this works wonders for me.
Topic archived. No new replies allowed.