C++读文件(大学考试难度)
#include<fstream>
#include<sstream>
这两个头文件 超重要
先简单解释下
fstream
—— 文件流,用来 操作文件。
sstream
—— 字符串流,用来 解析/拼接字符串。在后面的
ReadInfo
代码里:
ifstream file(filePath);
需要<fstream>
。
istringstream iss(line);
需要<sstream>
。接下来看具体示例,因该包含了大部分考试会碰到的
示例一:
text文件长这样:
对应读文件代码:
示例二:
text文件长这样:
对应读文件代码:
{ string teamA;//主队名称 int scoreA;//主队得分 int scoreB;//客队得分 string teamB;//客队名称 };struct goal{ string team;//队伍名称 int point;//积分 };// 接下来为读文件函数bool readInfo(string filename, vector<match>& matchs)//引用matchs这个向量{ifstream file(filename); //打开并将文件名filename的文件 读入 fileif (!file.is_open()){ return false; }struct match temp;while (file >> temp.teamA >> temp.scoreA >> temp.scoreB >>temp.teamB ){ matchs.push_back(temp); }file.close();return true; }
示例三:
struct info{string sfzh;//身份证号int ct; //Ct值};//1bool readInfo(string filename, vector<struct info>& infos){ifstream file(filename);if (!file.is_open()) return false; //这个逻辑应该不成立struct info temp;while (file >> temp.sfzh >> temp.ct){infos.push_back(temp);}file.close();return true;}
示例四:
i
#include <iostream> #include <fstream> #include <sstream> // istringstream 所需头文件 #include <string> #include <vector> using namespace std;int ReadInfo(const string& filePath, vector<vector<int>>& vecInt2D) {ifstream file(filePath); // 打开文件输入流if (!file.is_open()) { // 判断文件是否成功打开cerr << "无法打开文件: " << filePath << endl;return -1;}string line;while (getline(file, line)) // 按行读取文件内容{vector<int> vecInt; // 存储当前行的整数// 使用 istringstream 来解析这一行// istringstream 把字符串当作“输入流”处理// 这样我们就可以像从 cin 里提取数据一样,用 >> 运算符依次读取整数istringstream iss(line); int num;while (iss >> num) // 不断读取整数,直到行末{vecInt.push_back(num);}vecInt2D.push_back(vecInt); // 把当前行的数据存入二维 vector}file.close(); // 关闭文件return 1; // 成功返回 1 }
创建一个名为 file 的 ifstream 对象,并尝试打开 filePath 变量所指定路径的文件,以便进行后续的读取操作。
如果文件中的数据不是以空格、制表符或换行符分隔,而是以其他字符分隔(例如逗号),那么您需要使用不同的方法来读取和解析文件内容,例如使用 getline 函数配合 istringstream