C++/ C語言輸出格式

首先看C++的:

C++輸出對齊需要包含頭文件<iomanip>,當然對齊方式也分爲左右兩種:

 

#include <iostream>
#include<iomanip>
using namespace std;
 
int main()
{
	int a = 9999;
	int b = 999;
	int c = 99;
 
	//默認右對齊
	cout << "默認右對齊爲:\n";
	cout << setw(6) << a << endl;
	cout << setw(6) << b << endl;
	cout << setw(6) << c << endl;
 
	//現在改爲左對齊
	cout << "\n改爲左對齊後爲:\n";
	cout << left << setw(6) << a << endl;
	cout << left << setw(6) << b << endl;
	cout << left << setw(6) << c << endl;
 
	return 0;
}

 

若想在多餘位上填充字符,則: 

#include <iostream>
#include<iomanip>
using namespace std;
 
int main()
{
	int a = 9999;
	int b = 999;
	int c = 99;
 
	//默認右對齊
	cout << "默認右對齊爲:\n";
	cout.fill('#');//填充字符'#'
	cout << setw(6) << a << endl;
	cout << setw(6) << b << endl;
	cout << setw(6) << c << endl;
 
	//現在改爲左對齊
	cout << "\n改爲左對齊後爲:\n";
	cout.fill(' ');//取消字符填充
	cout << left << setw(6) << a << endl;
	cout << left << setw(6) << b << endl;
	cout << left << setw(6) << c << endl;
 
	return 0;
}

 

再看C語言的輸出格式:

#include<iostream>
using namespace std;
 
int main()
{
	int a = 9999;
	int b = 999;
	int c = 99;
 
	//默認右對齊
	printf("默認右對齊爲:\n");
	printf("%6d\n", a);
	printf("%6d\n", b);
	printf("%6d\n", c);
 
	//現在改爲左對齊
	printf("\n改爲左對齊後爲:\n");
	printf("%-6d\n", a);
	printf("%-6d\n", b);
	printf("%-6d\n", c);
 
	return 0;
}

 

輸出對齊有兩個方面,一是輸出寬度,一是左對齊還是又對齊。

在C++裏面,默認是右對齊,可以通過cout.setf(std::ios::left)調整爲左對齊,而且這種調整是全局的,一次設置,後面都有效。

但是對於輸出寬度的設置(使用cout.width(int i)設置)是一次性的,隻影響緊隨其後的一次輸出。

具體可以參看下面的代碼:

#include<iostream> int main(){ using std::cout; cout.setf(std::ios::left); int w = cout.width(); cout << "default field width = " << w << "\n"; cout.width(5); cout << "N" << ":"; cout.width(8); cout << "N * N" << "\n"; for (long i = 1; i <= 100; i *= 10){ cout.width(5); cout << i << ':'; cout.width(8); cout << i * i << "\n"; } return 0; }

在這方面C語言的就顯得簡單多了,printf("%5d"),輸出佔用5個字符寬度,且右對齊,printf("%-5d")輸出佔用5個字符寬度,且左對齊。都是什麼時候用就什麼時候設置。

還有一個問題就是,當實際的數據需要的寬度超出你設置的寬度的時候怎麼辦?

C++的選擇是,保證將數據顯示完整。

比如上面程序中的第8行:

C++中式優先保證把數據顯示完整。

C語言使用printf其實也是一樣的,優先保證把數據顯示完整。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章