2016-04-22 61 views
0

我需要从VS2013中的VC++中读取一个txt文件。从VS2013中的VC++中的多个节读取数据

在该文件中,有多发性部分:

#section1 
head1,head2,head3 
dcscsa, sdew, safce 
..... 
#section2 
head1,head2,head3, head4,head5 
112,633,788,632,235 
..... 

我需要保存行成不同的数据结构 为SECTION1: mapSection1>

for section12 
    mapSection2<string, map<string, int>> 

我可以使用的代码:

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? 
     } 

此外,我可以加载整个fi将其放入数据集中,然后在逐行读取文件时处理每行或处理每行。

哪一个更有效?

感谢

回答

0

我可以使用代码:...

不太。

使用:

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: 
     ... 

} 

另外,我可以整个文件加载到一个数据集,然后处理每个线或处理时,文件被读出一行行的每一行。

哪一个更有效?

几乎总是后者。