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