题
我正在解析包含字符串和数值的文件。我想按字段处理文件,每个文件都由空间或线结束字符界定。 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...
}
要获得想要的行为。
其他提示
输入流中可能有一个外观/推回的角色。 IIRC,寻求/讲述功能尚不清楚。
不隶属于 StackOverflow