我的目标是从文件中提取数据,将其拆分,并将其放入一个数组中以供将来修改。
下面是数据的样子:
course1-Maths|course1-3215|number-3|professor-Mark
sam|scott|12|H|3.4|1/11/1991|3/15/2012
john|rummer|12|A|3|1/11/1982|7/15/2004
sammy|brown|12|C|2.4|1/11/1991|4/12/2006
end_Roster1|我想把maths,3215,3和Mark放入一个数组中,然后是sam scott 12 H 3.4 1/11/1991 3/15/2012。
这就是我到目前为止所知道的:
infile.open("file.txt", fstream::in | fstream::out | fstream::app);
while(!infile.eof())
{
while ( getline(infile, line, '-') )
{
if ( getline(infile, line, '|') )
{
r = new data;
r->setRcourse_name(line);
r->setRcourse_code(3);//error not a string
r->setRcredit(3);//error not a string pre filled
r->setRinstructor(line);
cout << line << endl;
}
}
}然后,我尝试查看它,没有存储任何内容。
发布于 2012-05-14 01:46:06
首先,第1行与其余行非常不同,因此您需要对它们使用不同的解析算法。类似于:
bool first = true;
while(!infile.eof())
{
if (first)
{
// read header line
first = false;
}
else
{
// read lines 2..n
}
}读取行2..n可以通过为每行生成一个字符串流,然后使用'|‘作为分隔符将其传递给另一个getline来处理,以获得每个标记(sam,scott,12,H,3.4,1/11/1991,3/15/2012)
if (getline(infile, line, '\n'))
{
stringstream ssline(line);
string token;
while (getline(ssline, token, '|'))
vector.push_back(token);
}读取标题行将完全相同的概念再向前推进一步,然后使用另一个以'-‘为分隔符的getline进一步解析每个令牌。每次您将忽略第一个标记(course1、course1、number、professor),而使用第二个标记(Maths3215、3、Mark)。
发布于 2012-05-13 23:43:18
您完全忽略了在嵌套的while循环的条件中获取的行。您应该从while循环中的一个点调用getline,然后使用一系列if- then -else条件检查它的内容。
https://stackoverflow.com/questions/10572993
复制相似问题