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
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值