c++ - 将由空格分隔的数据读入结构数组
问题描述
我很难从 txt 文件中读取数据并将其转换为结构数组。数据的格式如下:
John Doe MATH 4 3 4 3 2
John Peterson MATH 5 5 3 6 2
...
目前,我只能读取不超过NLENGTH 个字符,其中应该是一个分隔符(至少在NLENGTH + 1 个位置)。但是,如果有一个名称/专业长于NLENGTH的记录,我的代码将停止正常工作。下面代码的输入如下所示:
John Doe # MATH # 4 3 4 3 2
John Peterson# MATH# 5 5 3 6 2
Michele Jordan # Electrical Engeeniring # 8 7 9 0 3 // Fail on this line
John Dore# MATH# 5 4 3 2 1
John Dore# Biology #9 3 4 2 3
const int NMARK = 5;
const int NLENGTH = 20;
const int NSTUDENT = 100;
const char dataDelimeter = '#';
void from_txtFile(const char *filename, Student *stArray)
struct Student {
char name[NLENGTH];
char major[NLENGTH];
int mark[NMARK];
};
int main()
{
Student stArray[NSTUDENT];
char fileName[20] = "data.txt";
from_txtFile(fileName, st);
}
void from_txtFile(const char *filename, Student *stArray) {
ifstream data(filename, ios::in);
int recordCount = 0;
if (!data) cout << "Error" << endl;
while (data && (recordCount < NSTUDENT)) {
data.getline(stArray[recordCount].name, NLENGTH, dataDelimeter);
data.getline(stArray[recordCount].major, NLENGTH, dataDelimeter);
for (int i = 0; i < NMARK; i++)
data >> stArray[recordCount].mark[i];
// Output
cout << stArray[recordCount].name << ' ';
cout << stArray[recordCount].major << ' ';
for (int i = 0; i < NMARK; i++)
cout << stArray[recordCount].mark[i] << ' ';
}
recordCount++;
data.close();
}
解决方案
推荐阅读
- python - python selenium,慢 xpath '所有元素'。添加超时
- python - 在 pypark 中写入 CSV 文件时选择编码
- sql - 如何更新表格以在数字的固定位置插入小数点?
- node.js - 如何使用 NYC 获得单元测试和集成测试的综合覆盖率
- qt - 用于拨号的 Qt MousePress/Release 过滤器
- python - Python - 每个日期和月份 PANDAS 的所有非零列的计数
- laravel - Laravel 不上传 svg 图片,即使它是允许的类型
- angular - 如何检测已被函数方法变异的材料表数据源的变化
- html - 为什么图像的来源没有改变?scrset 是如何工作的?
- javascript - Dropbox API:将自定义属性添加到文件时出错