C++基础:标准输入输出

来源:互联网 发布:vb.net 画图 线条粗细 编辑:程序博客网 时间:2024/06/08 17:03

标准库定义了4个IO对象,分别为cin, cout, cerr和clog。
cin为istream类型的对象,一般称为标准输入。
cout为ostream类型的对象,一般称为标准输出。
cerr为ostream类型的对象,称为标准错误。
clog为ostream类型的对象,一般用来输出一般性信息。

基础用法:

通常使用比较多的是cout,可以做信息输出,类比C中的printf ()。基础用法是

std::cout << "hello world" << std::endl;

运行结果:

[root@localhost 20170111]# ./a.out         hello world[root@localhost 20170111]# 

其中std::endl是操纵符的特殊值,他的作用是结束当前行并且将与设备关联的缓冲区中的内容刷到设备中,类比C中的‘\n’。当然‘\n’依然可以正常使用。

std::cout << "hello world"<< std::endl;std::cout << "hello world\n";

显示结果:

[root@localhost 20170113]# ./a.out            hello worldhello world[root@localhost 20170113]# 

同时连写的方式也是合法的

std::cout << "hello" <<' '<< "world" << '!' << v1 << std::endl; 

cin作为另外一个常用的输入,它从给定的istream读入数据,并存入给定对象中。
例如:

int v1;char v2;float v3;std::cin >> v1;std::cin >> v2;std::cin >> v3;std::cout << v1 << std::endl;std::cout << v2 << std::endl;std::cout << v3 << std::endl;

输入的时候需要与给定对象的数据类型对应,不然会出现错误。

另外与cout一样cin也是可以连写的:

std::cin >> v1 >> v2 >> v3;

达成效果与上面例子相同。

clog是标准错误流,与cout实现方式一样,一般作为输出错误信息,与cout使用方式一致。

cerr也是标准错误流,但是有一点与clog和cout不一样,cerr直接连接显示器,输出不经过缓冲区。clog和cout输出都需要经过缓冲区,只有写入控制符std::endl或缓冲区满才输出到屏幕。另外还有一点,cout可以将输出结果重定向到文件,cerr则不能。其余的使用方法cout,clog,cerr一致。

0 0