C++从文件中读取整数输入数据

主要记录下在刷题过程中遇到的简单输入问题,并没有考虑复杂的情况。看其他大神的博客写到 “如果你所要读的每一行的长度不超过255,程序运行也不会有问题”,似乎每行长度超过255会出现死循环,详情可参考:
运用ifstream的getline时需要注意的问题

用文件流 ifstream

主要用到 getlinestringstream

#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <algorithm>

using namespace std;

int main() {
    ifstream data("../data.txt"); //待读取文件的目录
    vector<int> res;
    string line;
    while (getline(data, line)) {
        stringstream ss; //输入流
        ss << line; //向流中传值
        if (!ss.eof()) {
            int temp;
            while (ss >> temp) //提取int数据
                res.push_back(temp); //保存到vector
        }
    }
    sort(res.begin(), res.end());
    cout << res.back() << " " << res.front() << endl;
    return 0;
}

这里是一个简单的示例,data.txt 中保存的数据是

1 2 3 4 5 6 7 8 -9
13 15 17 19 21 -2 -4 -6 -8
12 14 16 18 20 -1 -5 -7 -9

读入后所有数据都保存在一维的 vector 中。
结果输出最大值和最小值:

21 -9

用freopen重定向标准输入

#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <algorithm>

using namespace std;

int main() {
    vector<int> res;
    string line;
    freopen("../data.txt", "r", stdin); //以“只读访问”方式,将标准输入重定向到 “data.txt” 文件
    while (getline(cin, line)) {
        stringstream ss; //输入流
        ss << line; //向流中传值
        if (!ss.eof()) {
            int temp;
            while (ss >> temp) //提取int数据
                res.push_back(temp); //保存到vector
        }
    }
    fclose(stdin);
    sort(res.begin(), res.end());
    cout << res.back() << " " << res.front() << endl;
    return 0;
}

文件 data.txt 保存的数据是

1 2 3 4 5 6 7 8 -9
13 15 17 19 21 -2 -4 -6 -8
12 14 16 18 20 -1 -5 -7 -9

结果输出最大值和最小值:

21 -9
C++从文件读取数据通常涉及到文件操作的基本概念,如`ifstream`(输入文件流)或`fstream`(通用文件流)。以下是一个简单的步骤说明: 1. **包含头文件**: 首先,你需要包含 `<fstream>` 或 `<iostream>` 头文件,它们包含了处理文件操作所需的函数。 ```cpp #include <fstream> ``` 2. **创建文件流对象**: 使用 `ifstream` 类型创建一个文件流对象,并指定要读取的文件名。如果文件不存在,可能会抛出异常。 ```cpp std::ifstream file("example.txt"); // 假设文件名为 example.txt ``` 3. **检查文件是否打开成功**: 在继续之前,最好检查文件是否成功打开,可以使用 `good()` 函数来判断。 ```cpp if (!file.is_open()) { std::cerr << "Failed to open the file." << std::endl; return; // 或者处理错误 } ``` 4. **读取数据**: 使用 `getline()`、`>>` 运算符(用于读取整数、字符串等特定类型的数据)或 `read()` 函数从文件读取数据。 - 例如,读取文本行: ```cpp std::string line; getline(file, line); ``` - 例如,读取整数: ```cpp int value; file >> value; ``` 5. **关闭文件**: 当完成所有读取操作后,别忘了关闭文件以释放资源。 ```cpp file.close(); ``` 6. **异常处理**: 可能会遇到诸如文件损坏、磁盘空间不足等问题,因此建议始终使用异常处理机制。 ```cpp try { // 文件操作... } catch (const std::ifstream::failure& e) { std::cerr << "Error reading file: " << e.what() << std::endl; } ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值