cin
和cout
,类似与C语言中的scanf()
和printf()
cin
与>>
结合使用,用于读入用户输入,以空白(包括空格,回车,Tab)为分隔符,下面是一串示例代码
1 2 3 4 5 6 7 8 9
| char c1,c2 cin>>c1 cin>>c2
string s; float f cin>>s>>f
|
cout
与<<
结合使用,用于向控制台输出信息,可以将数据重定向输出到磁盘文件,下面是一串示例代码
1 2 3 4 5 6 7 8 9 10 11
| cout<<10<<endl; cout<<'a'<<endl; cout<<"C++"<<endl;
int a=10; cout<<a<<endl; int a=10; char *str = "abc"; cout<<a<<","<<str<<endl;
|
如何输出一些指定格式的数据,C++提供了一个标志位和操作符控制格式的头文件iomanip
,下面是一些常见的输出格式控制
1 2 3 4 5 6 7 8
| int a=10; cout<<"oct:"<<oct<<a<<endl; cout<<"dec:"<<dec<<a<<endl; cout<<"hex:"<<hex<<a<<endl;
double f=3.1415926; cout<<"默认输出:"<<f<<endl; cout<<"精度控制"<<setprecision(7)<<setiosflags(ios::fixed)<<f<<endl;
|
1 2 3 4 5 6 7 8 9 10 11
| #include <iostream> #include <iomanip> using namespace std; int main() { cout<<setw(10)<<3.1415<<endl; cout<<setw(10)<<setfill('0')<<3.1415<<endl; cout<<setw(10)<<setfill('0')<<setiosflags(ios:left)<<3.1415<<endl; cout<<setw(10)<<setfill('-')<<setiosflags(ios:left)<<3.1415<<endl; return 0; }
|
典例
要求:输入一个整数,输出其8进制值、10进制值、16进制值。
8进制值加前缀0
16进制值加前缀0x
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| #include<iostream> #include<iomanip> using namespace std;
int main() { int x; cin>>x; cout<<showbase <<oct<<x<<' ' <<dec<<x<<' ' <<hex<<x<<endl;
}
|
要求:输入5个小数,分别用左对齐,内部对齐,右对齐方式输出,宽度为10,保留2位小数,用””隔开。
样例输入
12.234 -655.456 -45.5 -45 6
样例输出
12.23 12.23 12.23
-655.46 - 655.46 -655.46
-45.50 - 45.50 -45.50
-45.00 - 45.00 -45.00
6.00 6.00 6.00
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| #include <iostream> #include <iomanip> using namespace std; int main() { double x; int c=5; while(c--) { cin>>x; cout << setprecision(2) << fixed; cout << setw(10) << left << x <<"" << setw(10) << internal << x <<"" << setw(10)<< right << x << endl; } return 0; }
|