流对象输入输出(cin/cout)

一、基础概念

cinstd::istream 类的输入流对象,用于从标准输入设备(通常是键盘)读取数据;

coutstd::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;
}

注意

  1. 取消同步后禁止混用 cin/cout 和 scanf/printf;
  2. 用 '\n' 替代 endl,避免刷新缓冲区;
  3. 优化代码写在 main 函数开头,先设置再执行输入输出;

建议全用 scanf / printf 或者全用 cin / cout。

三、常见问题

1. cin 和 getline 混用

cin >> 变量 会留下换行符,导致后续 getline 读取到空行

解决方案:用 cin.ignore() 清空缓冲区(见字符串示例)。

2. endl vs \n
  • endl:换行 + 刷新输出缓冲区(频繁使用会降低效率);
  • \n:仅换行(推荐日常使用,效率更高)。

下一篇再见👹

相关推荐
电子云与长程纠缠5 小时前
Godot学习05 - 播放与分离FBX动画
学习·游戏引擎·godot
蒸蒸yyyyzwd5 小时前
day3学习笔记
笔记·学习
2301_818419016 小时前
C++中的解释器模式变体
开发语言·c++·算法
爱学习的大牛1236 小时前
windows tcpview 类似功能 c++
c++
red_redemption6 小时前
自由学习记录(143)
学习
biter down7 小时前
C++11 统一列表初始化+std::initializer_list
开发语言·c++
楼田莉子7 小时前
MySQL数据库:MySQL的数据类型
数据库·学习·mysql
小陈phd8 小时前
系统架构师学习笔记(三)——计算机体系结构之存储系统
笔记·学习·系统架构
ShineWinsu8 小时前
爬虫对抗:ZLibrary反爬机制实战分析技术文章大纲
c++
Rsun045519 小时前
AI智能体学习路线
人工智能·学习