我正在尝试使用重载的“>>”来扫描文件中的输入。
问题是,我不知道如何处理文件结尾。 在这种情况下,我的文件由一个数字组成,后跟几个字符
例如:
9rl
8天
6ff
istream &operator>>(istream &is, Move &move)
{
char c;
int i = 0;
c = is.get();
if (!isalnum(c))
return;
move.setNum(c); // I convert the char to an int, but I'l edit it out
while ( (c = is.get()) != '\n')
{
move.setDirection(i, c); //sets character c into in array at index i
i++;
} // while chars are not newline
return is;
} // operator >>
当我将其作为常规函数时,字符为字母数字的测试有效,但在这里不起作用,因为它期望返回输入流。我也试过返回 NULL。有什么建议吗?
编辑:这是在一个 while 循环中调用的,所以我想找出一些方法让这个触发一些标志,这样我就可以跳出循环。在我之前的函数中,我让它返回一个 bool 值,如果成功则返回 true,如果字符不是字母数字则返回 false
最佳答案
返回是
。调用者应检查流是否有错误。
一定要适本地设置错误位:
std::istream &operator>>(std::istream &is, Move &move)
{
char c;
int i = 0;
c = is.get();
if (is.eof())
return is;
else if (c < '0' || c > '9') {
is.setstate(std::ios::badbit);
return is;
}
else
move.setNum(c-'0');
while ( (c = is.get()) != '\n' && is)
move.setDirection(i++, c);
if (c != '\n')
is.setstate(std::ios::badbit);
return is;
}
按如下方式使用它:
int main(int argc, char **argv)
{
std::stringstream s;
s << "9rl\n"
<< "8d\n"
<< "6ff\n";
s.seekg(0);
Move m;
while (s >> m)
std::cout << m;
if (s.bad())
std::cerr << argv[0] << ": extraction failed\n";
return 0;
}
请注意,代码仅在成功提取后使用实例 m
。
关于c++ - 摆脱重载的提取运算符? (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2234133/