0

My function to display a division table is working, but I want to format the output to allow any number of character preceding the decimal, but limiting the after decimal places to 2. Here is the code I am working with. Once I added the line cout.setf(std::ios::fixed, std::ios::floatfield) my data appears to be formatted correctly, but I am getting extra numbers appended to the front of the actual number. so instead of printing 1.00, the program prints 40981.00, and it does this for all the results. (the preceding number does change to 4102x.xx) x being the desired output.

void print_div_values(mult_div_values ** table, float x, float y){

cout << endl << "Here is the division table: " << endl;

for (int i = 1; i <= y; i++)        
{
    cout << endl;

    for (int j = 1; j <= x; j++)    
    {
        cout << std::setw(5) << cout.setf(std::ios::fixed, std::ios::floatfield) << std::setprecision(2) << table[i][j].div;        
    }
    cout << endl;
}

picture

2
  • 2
    Wouldn't a copy-paste do, why waste space? Commented Jan 7, 2015 at 18:43
  • Yes, sorry will do that next time. Commented Jan 8, 2015 at 0:14

1 Answer 1

5

std::ostream::setf returns the old flags, which are then formatted as an integer by cout. Use

cout.setf(std::ios::fixed, std::ios::floatfield);
cout << std::setw(5) << std::setprecision(2) << table[i][j].div;        
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the help. So my problem was the order and trying to do too many things in one line?
Sort of. If you want to do it in one line, you can write cout << setw(5) << setfixed << setprecision(2) << table[i][j].div; It's just that ostream::setf returns a number, and that was then printed; it's not a manipulator like the others.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.