iostream库
包含istream(输入流)和ostream(输出流)
流: 一个流就是从IO设备读入或写出的一个字符序列
类型名 | 作用 |
---|---|
cin | 标准输入 |
cout | 标准输出 |
cerr | 标准错误 |
clog | 一般信息 |
一个使用IO库的程序
提示用户输入两个数然后输出它们的和:
#include <iostream>
int main()
{
std::cout << "Enter two numbers:" << std::endl;
int v1 = 0, v2 = 0;
std::cin >> v1 >> v2;
std::cout << "The sum of" << v1 << "and" << v2 << "is" << v1 + v2 << std::endl;
return 0;
}
运行结果如图
语句分析
1 向流写入数据
std::cout << “Enter two numbers:” << std::endl;
- std:::避免与库中的命名向冲突,特地指明cout与endl属于名为std的定义空间中。(::为作用域运算符)
- <<:输出运算符。左侧必须为ostream对象(cout)。此句等价于
std::cout << “Enter two numbers:” ;
std::cout << std::endl; - “ Enter two numbers:”:字符串字面值常量
- endl:操作符,结束当前行将所有的输出写入流中。
2 从流读取数据
int v1 = 0, v2 = 0;
std::cin >> v1 >> v2;
- “int":定义v1.v2的类型
- “>>”:输入运算符,左侧必须为istream对象(cin)。此句等价于
std::cin >> v1 ;
std::cin >> v2;
练习
1编写程序,打印Hello World
#include <iostream>
int main()
{
std::cout << "Hello World" << std::endl;
return 0;
}
2使用”*“编写两个数的积
#include <iostream>
int main()
{
std::cout << "Enter two numbers:" << std::endl;
int v1 = 0, v2 = 0;
std::cin >> v1 >> v2;
std::cout << "The multiplication of" << v1 << "and" << v2 << "is" << v1 * v2 << std::endl;
return 0;
}
3分段输出例子中的语句
#include <iostream>
int main()
{
std::cout << "Enter two numbers:" << std::endl;
int v1 = 0, v2 = 0;
std::cin >> v1 >> v2;
std::cout << "The sum of"<<std::endl;
std::cout << v1 << std::endl;
std::cout <<"and" << std::endl;
std::cout <<v2 << std::endl;
std::cout <<"is"<<std::endl;
std::cout << v1 + v2 << std::endl;
return 0;
}
4解释下列语段是否合法?
- 不合法,”;“视为一条语句,因此后面语句不能共用第一条内的”std::cout"