输入输出

概念讲解

cin/cout

1234567891011121314#include <iostream>
using namespace std;

int main() {
    int a;
    cin >> a;
    
    double b;
    cin >> b;
    
    cout << a << " " << b << endl;
    
    return 0;
}

scanf/printf

12345678910111213#include <cstdio>

int main() {
    int a;
    scanf("%d", &a);
    
    double b;
    scanf("%lf", &b);
    
    printf("%d %.2f\n", a, b);
    
    return 0;
}

格式说明符

类型 格式符 示例
int %d scanf("%d", &a)
long long %lld scanf("%lld", &a)
float %f scanf("%f", &a)
double %lf scanf("%lf", &a)
char %c scanf("%c", &a)

输入优化

12ios::sync_with_stdio(false);
cin.tie(nullptr);

考点分析

初赛考查方式

  1. 选择题: 输入输出格式
  2. 程序阅读: 输入输出语句
  3. 填空题: 格式说明符

常见题型

  • 输入输出格式
  • 格式化输出
  • 输入优化

例题精讲

例题 1:基本输入输出

题目: 输入两个整数,输出它们的和。

解答:

123int a, b;
cin >> a >> b;
cout << a + b << endl;

例题 2:格式化输出

题目: 输出一个浮点数,保留 2 位小数。

解答:

123double a;
cin >> a;
printf("%.2f\n", a);

练习题

  1. scanf 和 cin 的区别是什么?
查看答案
特性 scanf cin
速度 较快 较慢(默认)
格式 需要格式说明符 自动识别类型
安全性 需要 & 取地址 更安全
可读性 格式复杂 简洁易读
  1. 如何输出一个整数,宽度为 10,右对齐?
查看答案

使用 setw 和 right:

12#include <iomanip>
cout << setw(10) << right << a << endl;

或使用 printf:

1printf("%10d\n", a);
  1. 如何提高 cin/cout 的速度?
查看答案

在 main 函数开头添加:

12ios::sync_with_stdio(false);
cin.tie(nullptr);

这会取消 C++ 流与 C 流的同步,提高输入输出速度。

注意:使用后不要混用 cin/cout 和 scanf/printf。

易错点

⚠️ 注意:

  1. scanf 要用 & 取地址
  2. double 用 %lf,float 用 %f
  3. endl 会刷新缓冲区,"\n" 不会
  4. 输入优化后不要混用 cin/cout 和 scanf/printf