Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/156.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 解析sstream_C++_Parsing_Sstream - Fatal编程技术网

C++ 解析sstream

C++ 解析sstream,c++,parsing,sstream,C++,Parsing,Sstream,我正在解析一个包含字符串和数值的文件。我希望逐个字段处理文件,每个字段由空格或行尾字符分隔。 ifstream::getline()操作只允许单个定界字符。因此,我当前所做的是使用字符“”作为分隔符的getline,如果遇到“\n”,则手动返回到流中的上一个位置: ifstream ifs ( filename , ifstream::in ); streampos pos; while (ifs.good()) { char curField[255]; pos =

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


多谢各位

输入流中可能有向前看/向后推字符。IIRC,seek/tell函数没有意识到这一点。

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

以获得您想要的行为。

似乎没有这样的角色。下面是一个失败的示例:它返回到字符#96,而不是#95:[87]48'0'字符[88]46.'char[89]49'1'字符[90]50'2'字符[91]55'7'字符[92]57'9'字符[93]52'4'字符[94]32'[95]48'0'字符[96]46.'char[97]48'0'字符[98]48'0'字符[99]52'4'字符[100]52'4'字符[101]55'7'字符[102]52'4'字符[103]54'6'字符[104]55'7'字符[105]10'␊'字符[106]32''字符。。。虽然似乎没有这样的未解释的字符,因此它不能完全回答这个问题,但我会接受答案,因为我的东西简单得多,而且效果很好:p谢谢!!实际上,我仍然对为什么我的代码不起作用感兴趣,因为我在其他地方也在使用它,在这种情况下,我需要检测换行符本身并单独处理它。。。。[还因为我很好奇为什么它不能正常工作!]@WhitAngl:我想你已经看过tellg的文档了,对吧?我不确定是什么问题。对于一个字符,您有什么不同的处理方法?我打开了文档,当然我也阅读了它。“get指针确定下一个输入操作要读取的输入序列中的下一个位置”。第一个getline(…,'')给出了正确的字符序列(因此可能以\n结尾),第二个getline(…,'\n')开始关闭一个字符,尽管seekg已将读取位置重置为第一个getline(…,'')的读取位置。所以我还是不明白。在我的另一个场景中,我在每个'\n'重置一个计数器。。。谢谢