Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting output in C++

Tags:

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?

like image 895
lovespeed Avatar asked Jun 27 '12 12:06

lovespeed


People also ask

What is formatted output in C?

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.

What is formatting output?

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.

What is %s %d %F in C?

%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].


1 Answers

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 
like image 73
stanri Avatar answered Oct 30 '22 18:10

stanri