C + + cout statement format control output __c++

Source: Internet
Author: User
Brief Introduction

In the Prinf () of the C language, the control output can be formatted. But the cout in C + + should be how to form the control output.

SETW (n) to control the preset width. SETW () only acts on the output immediately following it. If the input exceeds the length of the SETW () setting, output is based on the actual length. The default right alignment.

Setfill (char c), which is populated with the set character C if the width is already unused in the preset width.

Left and right, change the alignment. The default is right alignment.

fixed, using decimal notation

Setprecision (n) controls the precision of the output stream to display floating-point numbers, that is, the number of digits after the decimal point.

Scientific, use the scientific counting method.

Showpos, plus a plus sign before a positive number.


Example

#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
void Main ()
{
	double x[2][4] = {{1.2123, 0.1, 0.00021, 43.1}, {32.1, 0.4, 0.54302, 0.0003}};
	for (int i = 0; i < 2; i++) {for
		(int j = 0; J < 4; J +) {
			cout << setw (8) << setprecision (5) ;< fixed << left << Setfill (' 0 ') << x[i][j] << "T";
		cout << Endl;
	}
Results:


#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
void Main ()
{
	int x[2][4] = {1, 0, -1234, {}, {9871, $, 0}};
	for (int i = 0; i < 2; i++) {for
		(int j = 0; J < 4; J +) {
			cout << setw (8) << setprecision (5) & lt;< fixed << left <<  x[i][j] << "T";
		}
		cout << Endl;
	}



Visible, the data is aligned.

Note: Sometimes, when the N value in SETW (n) is smaller, the data will appear misaligned, and then the N value can be adjusted.

Welcome to my personal homepage, hello2019, view the original: http://richardliu.cn/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.