我在文本文件中有以下格式的数据。文件名 - empdata.txt请注意,行与行之间没有空格。
Sl|员工ID|姓名|部门|乐队|地点
1|327427|布罗克·麦克尼尔|研究与开发|U2|浦那
2|310456|Acton Golden|广告|P3|海得拉巴
3|305540|霍莉·卡马乔|薪资|U3|班加罗尔
4|218801|西蒙·迈尔斯|公共关系|U3|浦那
5|144051|伊顿本森|广告|P1|钦奈
我有一堂这样的课
class empdata
{
public:
int sl,empNO;
char name[20],department[20],band[3],location[20];
};
我创建了 empdata 类的对象数组。
如何从具有上述指定格式的 n 行数据的文件中读取数据并将其存储到创建的(类)对象数组中?
这是我的代码
int main () {
string line;
ifstream myfile ("empdata.txt");
for(int i=0;i<10;i++) //processing only first 10 lines of the file
{
getline (myfile,line);
//What should I do with this "line" so that I can extract data
//from this line and store it in the class object?
}
return 0;
}
所以基本上我的问题是如何从数据以“|”分隔的字符串中提取数据字符并将每个数据存储到单独的变量中
我更喜欢使用字符串工具包。字符串工具包将在解析时负责转换数字。
这是我将如何解决它。
#include <fstream>
#include <strtk.hpp> // http://www.partow.net/programming/strtk
using namespace std;
// using strings instead of character arrays
class Employee
{
public:
int index;
int employee_number;
std::string name;
std::string department;
std::string band;
std::string location;
};
std::string filename("empdata.txt");
// assuming the file is text
std::fstream fs;
fs.open(filename.c_str(), std::ios::in);
if(fs.fail()) return false;
const char *whitespace = " \t\r\n\f";
const char *delimiter = "|";
std::vector<Employee> employee_data;
// process each line in turn
while( std::getline(fs, line ) )
{
// removing leading and trailing whitespace
// can prevent parsing problemsfrom different line endings.
strtk::remove_leading_trailing(whitespace, line);
// strtk::parse combines multiple delimeters in these cases
Employee e;
if( strtk::parse(line, delimiter, e.index, e.employee_number, e.name, e.department, e.band, e.location) )
{
std::cout << "succeed" << std::endl;
employee_data.push_back( e );
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)