c++ - 格式化 .txt 文件中的字符串 (C++)
问题描述
我正在做一个任务,我的教授希望我打开并阅读一个包含不同字符串的 .txt 文件。我们应该格式化文件的内容。
例如:read_grade_file 方法有一个参数 int number_of_students
文件的第一行是“number_of_students 9”
我已经打开并阅读了文件并将每一行推入一个字符串向量。
如何自己获取第一行中的数字 9,以便使 number_of_students 参数等于它???请帮忙。
(我们可以跳过或删除向量中的任何不相关数据)。
我的代码:
void Read_Grade_File(string names[MAX_CLASS_SIZE][2], int scores[MAX_CLASS_SIZE][MAX_NUMBER_OF_ASSIGNMENTS], int *number_of_students, int *number_of_assignments, const string input_filename) {
string currline; // temporarily holds the content of each line read from the file
ifstream inFile; // filestream
vector<string> content; // vector containing each string from the file
inFile.open(input_filename); //open the file.
if (inFile.is_open()){
// reads file and pushes the content into a vector
while(!inFile.eof()){
getline(inFile, currline);
if(currline.size() > 0){
content.push_back(currline);
}
}
}
// prints the content stored in the vector
for (int i = 0; i < content.size(); i++){
cout << content[i] << endl;
}
}
解决方案
与其一次读取整行,不如在进行时读取行上的各种值可能更有意义。例如,如果您知道文件的格式,则可以读取第一个变量的名称,然后读取变量的值,如下所示:
std::string variableName;
int variableValue;
inFile >> variableName;
inFile >> variableValue;
因此,您可以获取您知道名称的变量,找到它们的值,然后循环读取文件的其余部分,读取那么多记录。
推荐阅读
- http - html中的代理url来渲染图像
- python - 已安装 numpy 但无法在 VSC 上导入
- android - 组件返回 RefreshControl 时的意外行为
- css - primeng primeflex 添加一个重置 css
- node.js - 使用 pdfmake 将多个页面添加到 pdf
- python - 断言所有输出 - 这是一个好习惯吗?
- java - 我在 Java 中遇到错误:无法解析为变量
- r - 如何用 R 连接数据框中的行?
- reactjs - 在更新查询期间,一些突变保持“待定”
- r - 为什么我的闪亮应用程序在使用自定义函数构建情节图时会发出警告:错误!:无效的参数类型错误?