c++输入输出总结

27 篇文章 0 订阅
这篇博客介绍了C++中处理不同输入输出场景的方法,包括一行输入多个数字、非空格分隔的字符串、多行指定行列的数据、已知列数的多行输入以及不统一格式的多行输入。示例代码展示了如何读取和处理这些数据,并提供了相应的输出示例。
摘要由CSDN通过智能技术生成

1. 一行输入未指定数量

输入

1 2 3 4 5
#include <bits/stdc++.h>
using namespace std;

int main() {
    // 输入:1 2 3 4 5
    string item;
    while (cin >> item) {
        cout << item << " ";
        if (getchar() == '\n') break;
    }
    return 0;
}

输出:

1 2 3 4 5

2. 一行输入非空格分割

输入

1_2_3_4_5
#include <bits/stdc++.h>
using namespace std;

int main() {
    //输入:1_2_3_4_5
    string data;
    getline(cin, data);
    stringstream ss(data);
    string item;
    while (getline(ss, item, '_')) {
        cout << item << ' ';
    }
    return 0;
}

输出:

1 2 3 4 5

3. 多行输入,指定行数列数

输入:

2 6
1 2 3 4 5 6
7 8 9 10 11 12
#include <bits/stdc++.h>
using namespace std;

int main() {
// 输入:
//2 6
//1 2 3 4 5 6
//7 8 9 10 11 12
    int rows, cols;
    cin >> rows >> cols;
    vector<vector<int>> data(rows);
    for (int i=0; i<rows; ++i) {
        for (int j=0; j<cols; ++j) {
            int temp;
            cin >> temp;
            data[i].push_back(temp);
        }
    }

    for (int i=0; i<rows; ++i) {
        for (int j=0; j<cols; ++j) {
            cout << data[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

输出:

1 2 3 4 5 6
7 8 9 10 11 12

4. 多行多列输入,列数已知,行数未知

牛客题目

输入示例:

1 5
10 20

输出示例:

6
30
#include <bits/stdc++.h>
using namespace std;

int main()
{
    int a,b;
    vector<vector<int>> inputs;
    while(cin >> a >> b) {
        vector<int> temp{a, b};
        inputs.push_back(temp);
    }
    
    for (auto &m : inputs) {
        cout << m[0] + m[1] << endl;
    }
    return 0;
}

在牛客上运行通过,在本地IDE最后需要使用Ctrl+d结束程序,才可以输出结果 

5. 多行输入,格式未统一

输入:

module3
module1, 10
module2, 5
module3, 10, module1, module2

解释:第一行是目标文件名,第二行开始,首先是一个文件名,后面试该文件的编译时间,再后面是该文件依赖的文件

输出:存放起来

#include <iostream>
#include <sstream>
#include <vector>
#include <unordered_map>
using namespace std;

int main() {
  string line;
  getline(cin, line);
  string target = line;

  string item;
  unordered_map<string, vector<string>> depends;
  unordered_map<string, int> times;
  char c;
  while (getline(cin, line)) {
    if (line.empty()) break;
    stringstream ss(line);
    int i = 0;
    string file;
    while (getline(ss, item, ',')) {
      if (i == 0) {
        i = 1;
        file = item;
        depends[file] = vector<string>{};
      }
      else if (i == 1) {
        i = 2;
        times[file] = atoi(item.c_str());
      }
      else {
        depends[file].push_back(item);
      }
    }
  }

  // 输出验证
  cout << "depends:" << endl;
  for (auto &m : depends) {
    cout << m.first << " ";
    for (auto &n : m.second) {
      cout << n << " ";
    }
    cout << endl;
  }

  return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值