流对象输入输出(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:仅换行(推荐日常使用,效率更高)。

下一篇再见👹

相关推荐
齐生113 小时前
iOS 知识点 - 渲染机制、动画、卡顿小集合
笔记
用户9623779544820 小时前
VulnHub DC-1 靶机渗透测试笔记
笔记·测试
樱木Plus2 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
齐生12 天前
iOS 知识点 - IAP 是怎样的?
笔记
tingshuo29172 天前
D006 【模板】并查集
笔记
tingshuo29173 天前
S001 【模板】从前缀函数到KMP应用 字符串匹配 字符串周期
笔记
blasit4 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_5 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星5 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛7 天前
delete又未完全delete
c++