C++、Python的输入输出及相关的处理操作

一、C++ 输入输出及相关处理操作

C++ 是算法竞赛中常用的语言,因其高效性适合处理大数据或严格时间限制的题目。输入输出是基础,但细节处理(如速度优化、格式要求)对比赛结果影响很大。

1. 基本输入输出

C++ 使用 <iostream> 库的 cincout 进行标准输入输出。

输入
  • 单变量输入
    cin 用于读取基本数据类型(如整数、浮点数、字符)。

    cpp 复制代码
    #include <iostream>
    using namespace std;
    int main() {
        int x;
        cin >> x; // 输入:5
        cout << x << endl; // 输出:5
        return 0;
    }
    • cin 自动跳过空白字符(空格、换行、制表符)。
    • 支持类型:int, long long, double, char, string
  • 多变量输入

    连续读取多个变量,用空格或换行分隔。

    cpp 复制代码
    int a, b;
    cin >> a >> b; // 输入:3 4
    cout << a + b << endl; // 输出:7
  • 读取字符串

    • 读取不含空格的字符串:

      cpp 复制代码
      string s;
      cin >> s; // 输入:hello
      cout << s << endl; // 输出:hello
    • 读取整行(含空格):

      cpp 复制代码
      string s;
      getline(cin, s); // 输入:hello world
      cout << s << endl; // 输出:hello world
      • 注意:如果之前用过 cin >>,需清除换行符:

        cpp 复制代码
        int x;
        cin >> x; // 输入:5
        cin.ignore(); // 清除换行符
        string s;
        getline(cin, s); // 输入:test case
        cout << x << " " << s << endl; // 输出:5 test case
输出
  • 基本输出
    cout 支持多种类型,endl 换行。

    cpp 复制代码
    int x = 123;
    cout << "Value: " << x << endl; // 输出:Value: 123
  • 格式化输出

    使用 <iomanip> 控制精度、宽度等。

    cpp 复制代码
    #include <iomanip>
    double pi = 3.14159;
    cout << fixed << setprecision(2) << pi << endl; // 输出:3.14
    int x = 42;
    cout << setw(5) << setfill('0') << x << endl; // 输出:00042
    • fixed:固定小数点格式。
    • setprecision(n):小数点后 n 位。
    • setw(n):输出宽度 n。
    • setfill(c):填充字符 c。
注意事项
  • cin/cout 速度较慢,处理大数据时需优化。
  • using namespace std; 简化代码,比赛中常用。

2. 加速输入输出

比赛中大数据量(如 10^6)可能导致 cin/cout 超时,需优化。

  • 关闭同步

    禁用 C++ 和 C 风格输入输出的同步,提升速度。

    cpp 复制代码
    #include <iostream>
    using namespace std;
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int n;
        cin >> n; // 输入:1000000
        cout << n << endl; // 输出:1000000
        return 0;
    }
    • cin.tie(nullptr) 解除 cincout 绑定。
    • 注意:启用后不能混用 scanf/printf
  • 使用 scanf/printf

    C 风格输入输出更快。

    cpp 复制代码
    #include <cstdio>
    int main() {
        int x;
        scanf("%d", &x); // 输入:123
        printf("%d\n", x); // 输出:123
        return 0;
    }
    • 常用格式:

      • %d:整数。
      • %lld:长整型。
      • %lf:双精度浮点数。
      • %c:字符。
      • %s:字符串。
    • 示例(多变量):

      cpp 复制代码
      int a, b;
      scanf("%d %d", &a, &b); // 输入:5 6
      printf("%d\n", a + b); // 输出:11
    • 读取字符串:

      cpp 复制代码
      char s[100];
      scanf("%s", s); // 输入:hello
      printf("%s\n", s); // 输出:hello
      • 含空格的字符串:

        cpp 复制代码
        char s[100];
        scanf(" %[^\n]", s); // 输入:hello world
        printf("%s\n", s); // 输出:hello world
  • 读取整行

    使用 fgets

    cpp 复制代码
    char s[100];
    fgets(s, 100, stdin); // 输入:test line
    printf("%s", s); // 输出:test line

3. 常见输入模式

比赛中输入格式多样,以下是典型场景及示例:

  • 固定数量输入

    读取 n 个数到数组。

    cpp 复制代码
    int n, a[100];
    cin >> n; // 输入:5
    for (int i = 0; i < n; i++) {
        cin >> a[i]; // 输入:1 2 3 4 5
    }
    for (int i = 0; i < n; i++) {
        cout << a[i] << " "; // 输出:1 2 3 4 5
    }
  • 不定数量输入

    读取直到文件末尾(EOF)。

    cpp 复制代码
    int x;
    while (cin >> x) { // 输入:1 2 3(手动结束或 EOF)
        cout << x << endl; // 输出:1\n2\n3
    }
    • 使用 scanf

      cpp 复制代码
      int x;
      while (scanf("%d", &x) != EOF) { // 输入:4 5 6
          printf("%d\n", x); // 输出:4\n5\n6
      }
  • 多组测试数据

    处理 T 组数据。

    cpp 复制代码
    int T;
    cin >> T; // 输入:2
    while (T--) {
        int n;
        cin >> n; // 输入:3
        cout << n * 2 << endl; // 输出:6
        // 第二组输入:4,输出:8
    }
  • 矩阵输入

    读取 n × m 矩阵。

    cpp 复制代码
    int n, m, a[100][100];
    cin >> n >> m; // 输入:2 3
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> a[i][j]; // 输入:1 2 3 4 5 6
        }
    }
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cout << a[i][j] << " "; // 输出:1 2 3 4 5 6
        }
        cout << endl;
    }

4. 处理特殊输入

  • 大整数

    使用 long long

    cpp 复制代码
    long long x;
    scanf("%lld", &x); // 输入:1234567890123
    printf("%lld\n", x); // 输出:1234567890123
    • 超大整数需字符串处理:

      cpp 复制代码
      string s;
      cin >> s; // 输入:999999999999999
      cout << s << endl; // 输出:999999999999999
  • 浮点数

    cpp 复制代码
    double x;
    scanf("%lf", &x); // 输入:3.14159
    printf("%.2lf\n", x); // 输出:3.14
  • 字符

    cpp 复制代码
    char c;
    scanf(" %c", &c); // 输入:A(空格跳过空白)
    printf("%c\n", c); // 输出:A
  • 字符串数组

    cpp 复制代码
    int n;
    cin >> n; // 输入:3
    string s[100];
    for (int i = 0; i < n; i++) {
        cin >> s[i]; // 输入:apple banana cherry
    }
    for (int i = 0; i < n; i++) {
        cout << s[i] << endl; // 输出:apple\nbanana\ncherry
    }

5. 常见输出技巧

  • 多解输出(空格分隔)

    cpp 复制代码
    int n = 3, ans[] = {1, 2, 3};
    for (int i = 0; i < n; i++) {
        cout << ans[i];
        if (i < n - 1) cout << " "; // 最后一个无空格
    }
    cout << endl; // 输出:1 2 3
  • 严格格式

    避免多余空格或换行。

    cpp 复制代码
    int n = 4, ans[] = {10, 20, 30, 40};
    printf("%d", ans[0]);
    for (int i = 1; i < n; i++) {
        printf(" %d", ans[i]);
    }
    printf("\n"); // 输出:10 20 30 40

6. 比赛注意事项

  • 文件输入输出

    cpp 复制代码
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    int x;
    cin >> x; // 从 input.txt 读
    cout << x << endl; // 写到 output.txt
    • 提交时注释掉 freopen
  • 边界情况

    • 示例(检查空输入):

      cpp 复制代码
      int n;
      cin >> n;
      if (n == 0) {
          cout << "Empty" << endl;
          return 0;
      }
    • 检查负数:

      cpp 复制代码
      int x;
      cin >> x; // 输入:-5
      cout << (x >= 0 ? x : -x) << endl; // 输出:5
  • 调试

    cpp 复制代码
    int x = 10;
    cout << "Debug: x = " << x << endl; // 输出:Debug: x = 10

二、Python 输入输出及相关处理操作

Python 因语法简洁和内置函数强大,适合初学者快速实现算法逻辑,但运行速度较慢,需注意优化。以下是详细讲解,每点附示例。

1. 基本输入输出

使用 input()print() 进行输入输出。

输入
  • 单变量

    python 复制代码
    x = int(input()) # 输入:7
    print(x) # 输出:7
    • input() 返回字符串,需转换类型。

    • 浮点数:

      python 复制代码
      x = float(input()) # 输入:2.5
      print(x) # 输出:2.5
  • 多变量

    python 复制代码
    a, b = map(int, input().split()) # 输入:3 4
    print(a + b) # 输出:7
  • 读取整行

    python 复制代码
    s = input() # 输入:hello world
    print(s) # 输出:hello world
  • 读取数组

    python 复制代码
    arr = list(map(int, input().split())) # 输入:1 2 3 4
    print(arr) # 输出:[1, 2, 3, 4]
输出
  • 基本输出

    python 复制代码
    x = 123
    print("Value:", x) # 输出:Value: 123
  • 控制分隔符和换行

    python 复制代码
    print(1, 2, 3, sep=',', end='!') # 输出:1,2,3!
  • 格式化输出

    • f-string:

      python 复制代码
      pi = 3.14159
      print(f"{pi:.2f}") # 输出:3.14
    • 宽度控制:

      python 复制代码
      x = 42
      print(f"{x:05d}") # 输出:00042

2. 加速输入输出

Python 输入输出较慢,需优化。

  • 快速输入

    使用 sys.stdin.readline

    python 复制代码
    import sys
    input = sys.stdin.readline
    x = int(input()) # 输入:1000000
    print(x) # 输出:1000000
    • 读取数组:

      python 复制代码
      arr = list(map(int, input().split())) # 输入:1 2 3
      print(arr) # 输出:[1, 2, 3]
    • 去除换行符:

      python 复制代码
      s = input().strip() # 输入:test\n
      print(s) # 输出:test
  • 读取多行

    python 复制代码
    import sys
    lines = sys.stdin.readlines()
    for line in lines:
        print(line.strip()) # 输入:line1\nline2\n,输出:line1\nline2
  • 输出优化

    集中输出:

    python 复制代码
    ans = [1, 2, 3]
    print(' '.join(map(str, ans))) # 输出:1 2 3

3. 常见输入模式

  • 固定数量

    python 复制代码
    n = int(input()) # 输入:4
    arr = list(map(int, input().split())) # 输入:5 6 7 8
    print(sum(arr)) # 输出:26
  • 不定数量

    python 复制代码
    while True:
        try:
            x = int(input()) # 输入:1 2 3(手动结束)
            print(x) # 输出:1\n2\n3
        except EOFError:
            break
  • 多组测试数据

    python 复制代码
    T = int(input()) # 输入:2
    for _ in range(T):
        n = int(input()) # 输入:5
        print(n * 2) # 输出:10
        # 第二组输入:3,输出:6
  • 矩阵输入

    python 复制代码
    n, m = map(int, input().split()) # 输入:2 3
    matrix = [list(map(int, input().split())) for _ in range(n)] # 输入:1 2 3 4 5 6
    print(matrix) # 输出:[[1, 2, 3], [4, 5, 6]]

4. 处理特殊输入

  • 大整数

    Python 无整数范围限制:

    python 复制代码
    x = int(input()) # 输入:999999999999
    print(x) # 输出:999999999999
  • 浮点数

    python 复制代码
    x = float(input()) # 输入:3.14159
    print(f"{x:.2f}") # 输出:3.14
  • 字符串与字符

    python 复制代码
    s = input() # 输入:abc
    for c in s:
        print(c) # 输出:a\nb\nc

5. 常见输出技巧

  • 多解输出

    python 复制代码
    ans = [1, 2, 3]
    print(*ans) # 输出:1 2 3
  • 严格格式

    python 复制代码
    ans = [10, 20, 30]
    print(' '.join(map(str, ans))) # 输出:10 20 30

6. 比赛注意事项

  • 文件输入输出

    python 复制代码
    import sys
    sys.stdin = open("input.txt", "r")
    sys.stdout = open("output.txt", "w")
    x = int(input()) # 从 input.txt 读
    print(x) # 写到 output.txt
  • 效率

    • 避免字符串拼接:

      python 复制代码
      ans = []
      for i in range(3):
          ans.append(str(i))
      print(' '.join(ans)) # 输出:0 1 2
  • 异常处理

    python 复制代码
    while True:
        try:
            n = int(input()) # 输入:5
            print(n) # 输出:5
        except:
            break
  • 调试

    python 复制代码
    x = 10
    print(f"Debug: x = {x}", file=sys.stderr) # 输出到错误流

三、比赛中常见技巧与注意事项

  1. 模板化

    • 准备常用输入输出模板,比赛时直接调用,节省时间。

    • 示例(C++):

      cpp 复制代码
      #include <bits/stdc++.h>
      using namespace std;
      int main() {
          ios::sync_with_stdio(false);
          cin.tie(nullptr);
          int n;
          cin >> n;
          vector<int> a(n);
          for (int i = 0; i < n; i++) cin >> a[i];
          // 逻辑代码
          return 0;
      }
    • 示例(Python):

      python 复制代码
      import sys
      input = sys.stdin.readline
      n = int(input())
      arr = list(map(int, input().split()))
      # 逻辑代码
  2. 边界检查

    • 输入是否为空。
    • 数据范围是否超出 int(需用 long long 或 Python)。
    • 数组是否越界。
  3. 格式要求

    • 注意空格、换行、末尾是否多余。
    • 严格按题目要求输出(如无多余空格)。
  4. 时间优化

    • 使用快速输入输出。
    • 避免不必要的循环或递归。

相关推荐
pixel33 分钟前
C++多线程系统编程
c++
啥都鼓捣的小yao17 分钟前
Python在糖尿病分类问题上寻找具有最佳 ROC AUC 分数和 PR AUC 分数(决策树、逻辑回归、KNN、SVM)
python·决策树·机器学习·支持向量机·分类·逻辑回归
拖拉机23 分钟前
Python(七)函数
后端·python
E-iceblue25 分钟前
通过 Python 在PDF中添加、或删除超链接
python·python pdf库·pdf超链接
2401_8906661328 分钟前
免费送源码:Java+ssm+MySQL 校园二手书销售平台设计与实现 计算机毕业设计原创定制
java·spring boot·python·mysql·小程序·php·课程设计
SHIPKING39336 分钟前
【LangChain少样本提示工程实战】FewShotPromptTemplate原理与应用解析——附运行代码
数据库·python·langchain·llm·fewshotprompt
ll7788111 小时前
C++学习之路,从0到精通的征途:string类的模拟实现
开发语言·数据结构·c++·学习·算法·职场和发展
ShAn DiAn1 小时前
C++ 重构muduo网络库
网络·c++·网络协议
豆豆1 小时前
day24 学习笔记
笔记·python·opencv·学习
辰阳星宇1 小时前
213、【图论】有向图的完全联通(Python)
开发语言·python·图论