2

I've created a program that displays multiplication table:

for (int a=1; a<=10; a++)
{
    cout << endl;
    for (int b=1; b<=10; b++)
    {
        cout << " [" << a*b <<"]   ";
    }
}

The problem is it displays it like this:

img

I've tried to use setw() but it doesn't work since it sets it to all the numbers so it just makes the result spaced out a little bit more. Anything else i can try?

Arty
  • 14,883
  • 6
  • 36
  • 69
Dano
  • 55
  • 6
  • 2
    All questions here should have all relevant information ***in the question itself as plain text***. Links can stop working at any time making questions meaningless. Code, data, or errors, shown as images cannot be copy/pasted; or edited or compiled for further research and investigation. Please [edit] this question, removing and replacing all links and images with all relevant information as plain text. All code must meet all requirements of a [mre]. You can find many other questions here that explain everything in plain text, please use them as an example for how your question should look. – Sam Varshavchik Nov 03 '20 at 15:03
  • 1
    maybe using tab special character `\t` will work for you? – pptaszni Nov 03 '20 at 15:04
  • @SamVarshavchik Sorry, I've never used this site before and didn't know that. – Dano Nov 03 '20 at 15:13
  • 1
    You either need to use tab characters (which then depends on terminals settings, since tabs can be set) or work out the width of `a*b` and subsequently output a number of space characters based on that width (e.g. if `a*b` is one digit, the number of spaces to be output before/after it will be one more than would be the case if `a*b` has two digits). – Peter Nov 03 '20 at 15:15

1 Answers1

7

If you look at the documentation for setw you will note that you need to stream it to your stream like so:

cout  << " [" << setw(3) << a*b <<"]   ";

Here is a live example.

If you need to calculate the size that you need for the stream width, you can look up a question like this:

Efficient way to determine number of digits in an integer

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175