c++的标准流入流出和使用例子

参考链接

标准输出流(cout)

预定义的对象 cout 是 iostream 类的一个实例。cout 对象"连接"到标准输出设备,通常是显示屏。cout 是与流插入运算符 << 结合使用的,如下所示:

 1 #include <iostream>
 2  
 3 using namespace std;
 4  
 5 int main( )
 6 {
 7    char str[] = "Hello C++";
 8  
 9    cout << "Value of str is : " << str << endl;
10 }
View Code

标准输入流(cin)

预定义的对象 cin 是 iostream 类的一个实例。cin 对象附属到标准输入设备,通常是键盘。cin 是与流提取运算符 >> 结合使用的,如下所示:

 1 #include <iostream>
 2  
 3 using namespace std;
 4  
 5 int main( )
 6 {
 7    char name[50];
 8  
 9    cout << "请输入您的名称: ";
10    cin >> name;
11    cout << "您的名称是: " << name << endl;
12  
13 }
View Code

标准错误流(cerr)

预定义的对象 cerr 是 iostream 类的一个实例。cerr 对象附属到标准错误设备,通常也是显示屏,但是 cerr 对象是非缓冲的,且每个流插入到 cerr 都会立即输出。

 1 #include <iostream>
 2  
 3 using namespace std;
 4  
 5 int main( )
 6 {
 7    char str[] = "Unable to read....";
 8  
 9    cerr << "Error message : " << str << endl;
10 }
View Code

结果:Error message : Unable to read....

标准日志流(clog)

预定义的对象 clog 是 iostream 类的一个实例。clog 对象附属到标准错误设备,通常也是显示屏,但是 clog 对象是缓冲的。这意味着每个流插入到 clog 都会先存储在缓冲在,直到缓冲填满或者缓冲区刷新时才会输出。

 1 #include <iostream>
 2  
 3 using namespace std;
 4  
 5 int main( )
 6 {
 7    char str[] = "Unable to read....";
 8  
 9    clog << "Error message : " << str << endl;
10 }
View Code
 1 #include <iostream>
 2 #include <iomanip>
 3 using namespace std;
 4 int main()
 5 {
 6     cout<<setiosflags(ios::left|ios::showpoint);  // 设左对齐,以一般实数方式显示
 7     cout.precision(5);       // 设置除小数点外有五位有效数字 
 8     cout<<123.456789<<endl;
 9     cout.width(10);          // 设置显示域宽10 
10     cout.fill('*');          // 在显示区域空白处用*填充
11     cout<<resetiosflags(ios::left);  // 清除状态左对齐
12     cout<<setiosflags(ios::right);   // 设置右对齐
13     cout<<123.456789<<endl;
14     cout<<setiosflags(ios::left|ios::fixed);    // 设左对齐,以固定小数位显示
15     cout.precision(3);    // 设置实数显示三位小数
16     cout<<999.123456<<endl; 
17     cout<<resetiosflags(ios::left|ios::fixed);  //清除状态左对齐和定点格式
18     cout<<setiosflags(ios::left|ios::scientific);    //设置左对齐,以科学技术法显示 
19     cout.precision(3);   //设置保留三位小数
20     cout<<123.45678<<endl;
21     return 0; 
22 }
View Code

以上是输入输出流中的函数(模板):

猜你喜欢

转载自www.cnblogs.com/fanhua666/p/11506911.html