我是靠谱客的博主 贪玩秋天,这篇文章主要介绍C++的输入与输出和格式化输出,现在分享给大家,希望可以做个参考。

一、C++ 输入与输出 格式化输出

1.cin与cout

2.格式化输出

2.1设置域宽及位数

对于实型,cout 默认输出六位有效数据,setprecision(2) 可以设置有效位数,setprecision(n)<<setiosflags(ios::fixed)合用,可以设置小数点右边的位数。

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
	printf("%cn%dn%fn",'a',100,120.00);
	printf("%5cn%5dn%6.2fn",'a',100,120.00);
	cout
	<<setw(5)<<'a'<<endl
	<<setw(5)<<100<<endl
	<<setprecision(2)<<setiosflags(ios::fixed)<<120.00<<endl;
	return 0;
}

2.2按进制输出

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
	int i = 123;
	cout<<i<<endl;
	cout<<dec<<i<<endl;
	cout<<hex<<i<<endl;
	cout<<oct<<i<<endl;
	cout<<setbase(16)<<i<<endl;
	return 0;
}

2.3设置填充符

可以设置域宽的同时,设置左右对齐及填充字符。

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
	cout<<setw(10)<<1234<<endl;
	cout<<setw(10)<<setfill('0')<<1234<<endl;
	cout<<setw(10)<<setfill('0')<<setiosflags(ios::left)<<1234<<endl;
	cout<<setw(10)<<setfill('-')<<setiosflags(ios::right)<<1234<<endl;
	return 0;
}

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注靠谱客的更多内容!

最后

以上就是贪玩秋天最近收集整理的关于C++的输入与输出和格式化输出的全部内容,更多相关C++内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(87)

评论列表共有 0 条评论

立即
投稿
返回
顶部