在写C++ 输入输出实例前,有几个概念需要理解:1、C++用一个标准库来提供IO机制,这里用到iostream库,它包含两个基础类型istream和ostream,即分别是输入流和输出流。2、标准库定义了四个IO对象,分别是cin(标准输入)、cout(标准输出)、cerr(标准错误)和clog。其中cerr用来输出警告和错误信息,跟C语言的perror类似,clog用来输出程序运行时的 一般信息。接下来以一个实例来解释具体怎么操作。
一个简单的程序:
#include <iostream>
int main(){
int x = 0, y = 0;
std : : cout << "input two num" << std : : endl;
std : : cin >> x >> y ;
std : : cout << "the sum of " << x <<" and " << y <<" is " << x+y << std : : endl;
return 0;}
1、声明包含一个标注库:iostream
2、<<:输出运算符,左边接cout(标准输出),右边接要输出的对象(字符串用双引号),运算结果为运算符左侧对象,即返回cout。所以输出语句也可以等价为:
std : : cout << "the sume of ";
std : : cout << x;
std : : cout << "and";
......
输入运算符>>类似。
3、endl:结束操纵符,结束当前行。
4、前缀std : : 指出cout和endl是定义在std的命名空间。