一、基础概念
cin:std::istream类的输入流对象,用于从标准输入设备(通常是键盘)读取数据;
cout:std::ostream类的输出流对象,用于向标准输出设备(通常是屏幕)写入数据;头文件:使用
cin/cout必须包含<iostream>头文件,且建议加上using namespace std;,否则需写std::cin/std::cout。
二、用法
1. 读取/输出整型、浮点型
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int a, b;
cin >> a >> b; //多变量输入
cout << a << ' ' << b << '\n'; //多变量输出
// 输入:2 3 输出:2 3
double c, d;
cin >> c >> d;
cout << c << ' ' << d << '\n';
// 输入:2 3 输出:2 3(double默认格式省略末尾0)
return 0;
}
2. 读取 / 输出字符串
-
方式 1:
cin >> 字符串:读取到空格 / 回车为止(不包含空格); -
方式 2:
getline(cin, 字符串):读取一整行(包含空格)。#include <iostream>
#include <string>
using namespace std;int main()
{
// 读取单个字符
char ch;
cin >> ch;
// 输入:a 输出:a(自动跳过空格,只读取第一个有效字符)
cout << ch << '\n';// 方式1:读取字符数组(遇空格停止) char s[10]; cin >> s; // 输入:hello world 输出:hello(空格后的内容被截断) cout << s << '\n'; // 注意:cin读取后会残留换行符,需清空缓冲区避免影响后续getline cin.ignore(); // 方式2:读取整行字符串(包含空格) string str; getline(cin, str); // 输入:hello world 输出:hello world(读取到换行符为止) cout << str << '\n'; return 0;}
3. 格式控制
通过 iomanip 头文件的工具控制输出格式(如小数位数、对齐方式):
#include <iostream>
#include <iomanip> // 格式控制需包含此头文件
using namespace std;
int main() {
double pi = 3.1415926;
// 1. 控制小数位数(fixed + setprecision(n))
cout << pi << '\n'; // 输出 3.14159
cout << fixed << setprecision(2) << pi << '\n'; // 保留2位小数:3.14
cout << setprecision(4) << pi << '\n'; // 保留4位小数:3.1416(四舍五入)
// 2. 设置输出宽度(setw(n)):仅对下一个输出有效
int num = 123;
cout << setw(5) << num << '\n'; //(宽度为5,右对齐)输出 " 123"
cout << left << setw(5) << num << '\n'; //(宽度为5,左对齐)输出 "123 "
return 0;
}
4. 取消同步流(提高效率)
#include<bits/stdc++.h>
using namespace std;
int main()
{
//取消同步流
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
//其他操作不变
int x;
cin >> x;
cout << x << '\n';
return 0;
}
注意
- 取消同步后禁止混用 cin/cout 和 scanf/printf;
- 用 '\n' 替代 endl,避免刷新缓冲区;
- 优化代码写在 main 函数开头,先设置再执行输入输出;
建议全用 scanf / printf 或者全用 cin / cout。
三、常见问题
1. cin 和 getline 混用
cin >> 变量 会留下换行符,导致后续 getline 读取到空行
解决方案:用 cin.ignore() 清空缓冲区(见字符串示例)。
2. endl vs \n
endl:换行 + 刷新输出缓冲区(频繁使用会降低效率);\n:仅换行(推荐日常使用,效率更高)。
下一篇再见👹