I need to read a txt file from VC++ in VS2013.
In the file, there are mutiple sections:
#section1
head1,head2,head3
dcscsa, sdew, safce
.....
#section2
head1,head2,head3, head4,head5
112,633,788,632,235
.....
I need to save the lines into different data structure for section1: mapSection1>
for section12
mapSection2<string, map<string, int>>
Can I use the code :
string aLine;
getline(file, aLine);
stringstream ss(aLine);
int cnt = 0;
if (file.good())
{
while (!file.eof())
{
string substr;
getline(file, aLine);
stringstream ss(aLine);
while (ss.good())
{
// how to save data to different map for different section?
}
Also, i can load the whole file into a data set and then process each line or process each line when the file was read line by line.
Which one is more efficient ?
thanks
Can I use the code : ...
Not quite.
Use:
int sectionNo = 0;
while (getline(file, aLine))
{
if (aLine.empty()) continue;
if (aLine[0] == '#')
{
++sectionNo;
getline(file, aLine); // read headings... use them if you like
continue;
}
std::stringstream ss(aLine);
switch (sectionNo)
{
case 1:
if (ss >> a >> b >> c >> std::skipws && ss.eof())
... use a, b, c ...
else
throw std::runtime_error("invalid data in section 1 " + aLine);
break;
case 2:
...
}
Also, i can load the whole file into a data set and then process each line or process each line when the file was read line by line.
Which one is more efficient ?
Almost always the latter.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.