c++ - 解析 sstream

标签 c++ parsing sstream

我正在解析一个包含字符串和数值的文件。我想逐个字段处理文件,每个字段由空格或行尾字符分隔。 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”似乎将流定位到一个字符太晚了(因此我错过了每个换行符之前每个字段的第一个字符)。 我知道还有其他方法可以通过逐行扫描等方式对此类解析器进行编码,但我真的很想了解为什么这段特殊的代码会失败...

非常感谢!

最佳答案

正如 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...
 }

获得你想要的行为。

关于c++ - 解析 sstream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3868873/

相关文章:

c++ - 配置用 C++ 编写的现有应用程序

c++ - 将字符串转换为 int 使用 sstream

c++ - 聚合 'std::stringstream out' 的类型不完整,无法定义 [C++]

c++ - 如何将结果从std::thread传回给Qt中的Gui主线程?

c++ - 这是 struct hack 的 C++ 替代品吗?

c++ - 只为一种widget设置样式

c++ - 何时在成员函数中使用 "this"指针

c# - 我应该为失败的文件解析抛出什么异常?

python - Python 程序如何加载并读取文件中的特定行?

c++ - 接收二进制数据并写入(C++套接字编程)