1

我正在解析一个包含字符串和数值的文件。我想逐个字段处理文件,每个字段由空格或行尾字符分隔。ifstream::getline() 操作只允许使用单个分隔符。因此,我目前所做的是以字符 ' ' 作为分隔符的 getline,然后在遇到 '\n' 时手动返回到流中的上一个位置:

 ifstream ifs ( filename , ifstream::in );
 streampos pos;
 while (ifs.good())
 {  
  char curField[255];  

  pos = ifs.tellg();
  ifs.getline(curField, 255, ' '); 
  string s(curField);
  if (s.find("\n")!=string::npos) 
  {   
   ifs.seekg(pos); 
   ifs.getline(curField, 255, '\n'); 
   s = string(curField);
  }

 // process the field contained in the string s...
 }

但是,“seekg”似乎将流定位为一个字符为时已晚(因此我错过了每个换行符之前每个字段的第一个字符)。我知道还有其他方法可以通过逐行扫描等方式来编写这样的解析器,但我真的很想了解为什么这段特定的代码会失败……

非常感谢你!

4

2 回答 2

0

输入流中可能存在前瞻/后推字符。IIRC,寻找/告诉功能不知道这一点。

于 2010-10-06T01:18:15.947 回答
0

正如 Loadmaster 所说,可能有下落不明的字符,或者这可能只是一个错误的错误。

但这只是不得不说......你可以替换这个:

 ifstream ifs ( filename , ifstream::in );
 streampos pos;
 while (ifs.good())
 {  
  char curField[255];  

  pos = ifs.tellg();
  ifs.getline(curField, 255, ' '); 
  string s(curField);
  if (s.find("\n")!=string::npos) 
  {   
   ifs.seekg(pos); 
   ifs.getline(curField, 255, '\n'); 
   s = string(curField);
  }

 // process the field contained in the string s...
 }

有了这个:

 ifstream ifs ( filename , ifstream::in );
 streampos pos;
 string s;
 while (ifs.good())
 {  
   ifs >> s;
   // process the field contained in the string s...
 }

得到你想要的行为。

于 2010-10-06T01:28:57.997 回答