In a C++ code I have a matrix of double variables which I print out. However because all of them have different number of digits, the output format is destroyed. One solution is to do cout.precision(5)
but I want different columns have a different precision. Also, because there are negative values in some cases, the presence of the -
sign also causes problems. How to get around this and produce a properly formatted output?
The C language comes with standard functions printf() and scanf() so that a programmer can perform formatted output and input in a program. The formatted functions basically present or accept the available data (input) in a specific format.
Several library functions help you convert data values from encoded internal representations to text sequences that are generally readable by people. You provide a format string as the value of the format argument to each of these functions, hence the term formatted output.
%s refers to a string %d refers to an integer %c refers to a character. Therefore: %s%d%s%c\n prints the string "The first character in sting ", %d prints i, %s prints " is ", and %c prints str[0].
Off the top of my head, you can use setw(int) to specify the width of the output.
like this:
std::cout << std::setw(5) << 0.2 << std::setw(10) << 123456 << std::endl; std::cout << std::setw(5) << 0.12 << std::setw(10) << 123456789 << std::endl;
gives this:
0.2 123456 0.12 123456789
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With