C++文件读取:常见的ACM输入格式读取二维数组

C++文件读取:常见的ACM输入格式读取

文件流头文件fstream

在C++中,对文件的操作是通过stream的子类fstream(file stream)来实现的,所以,要用这种方式操作文件,就必须加入头文件fstream.h。下面就把此类的文件操作过程一一道来。

代码演示

image-20220505230142157

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    int arr[100][100];
    ifstream ifs("in.txt"); 
    int r,c;
    ifs >> r >> c;
    cout << r << " " << c << endl;
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            ifs >> arr[i][j];
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

输出:

2 4
1 2 3 4
5 6 7 8
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将一个以逗号分隔的 CSV 格式文件读取到二维数组中,你可以使用 C++ 的文件输入流和字符串分割操作。 下面是一个示例代码,展示如何实现这个功能: ```cpp #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <string> std::vector<std::vector<std::string>> readCSV(const std::string& filename) { std::ifstream file(filename); std::vector<std::vector<std::string>> data; if (file) { std::string line; while (std::getline(file, line)) { std::vector<std::string> row; std::stringstream lineStream(line); std::string cell; while (std::getline(lineStream, cell, ',')) { row.push_back(cell); } data.push_back(row); } file.close(); } else { std::cout << "Failed to open file: " << filename << std::endl; } return data; } int main() { std::string filename = "path/to/csv/file.csv"; std::vector<std::vector<std::string>> data = readCSV(filename); // 输出读取到的二维数组 for (const auto& row : data) { for (const auto& cell : row) { std::cout << cell << " "; } std::cout << std::endl; } return 0; } ``` 在这个例子中,我们定义了一个 `readCSV()` 函数,该函数接受 CSV 文件的路径作为输入参数,并返回一个二维字符串向量表示的数据。 在 `readCSV()` 函数中,我们首先打开文件,然后逐行读取文件内容。对每一行,我们使用 `std::getline()` 函数和逗号作为分隔符来分割字符串,将每个单元格的内容存储到一个字符串向量中。最后,将每一行的字符串向量添加到二维数据向量中。 在 `main()` 函数中,我们调用 `readCSV()` 函数来读取 CSV 文件,并将结果存储在 `data` 变量中。然后,我们遍历二维数据向量并打印出每个单元格的内容。 记得在使用这段代码时,要包含 `<iostream>`、`<fstream>`、`<sstream>` 和 `<vector>` 头文件

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值