我正在解析一个包含字符串和数值的文件。我想按字段处理文件字段,每个字段由空格或行尾字符分隔。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“似乎定位流一个字符太晚了(因此,我错过了每个字段的第一个字符在每一行中断之前)。我知道还有其他方法来编写这样的解析器,逐行扫描等等,但是我真的很想了解为什么这个特定的代码会失败.
非常感谢!
发布于 2010-10-06 01:28:57
正如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-06 01:18:15
输入流中可能有向前/后推字符。IIRC,搜索/告知函数不知道这一点。
https://stackoverflow.com/questions/3868873
复制相似问题