摆脱超载的提取运算符? (C++)
我正在尝试使用重载的“>>”扫描文件中的输入。
问题是,我不知道如何处理文件结尾。 在这种情况下,我的文件由一个数字组成,后跟几个字符
例如:
9rl
8d
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 循环中调用的,所以我试图找出某种方法来让这个触发一些标志,以便我可以跳出循环。在我之前的函数中,我返回一个布尔值,如果成功则返回 true,如果字符不是字母数字则返回 false
I'm trying to use an overloaded ">>" to scan input from a file.
The problem is, I have no idea how to deal with end of file.
In this case, my file is composed of a number, followed by several chars
Ex:
9rl
8d
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 >>
The test for the character being alpha numeric worked when I had this as a regular function, but doesn't work here as it expects an input stream to be returned. I've tried returning NULL as well. Suggestions?
EDIT: this is being called in a while loop, So i'm trying to figure out some way to have this trigger some flag so that I can break out of the loop. In my previous function, I had this return a boolean, returning true if successful or false if the character was not alphanumeric
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
返回
是
。调用者应该检查流是否有错误。请务必根据需要设置错误位:
按以下方式使用它:
请注意,代码仅在成功提取后才使用实例
m
。Return
is
. Callers should check the stream for errors.Be sure to set error bits as appropriate:
Use it as in the following:
Notice that the code uses the instance
m
only after successful extraction.您可以将流的标志设置为诸如 ios::bad 或 ios::fail 使用 ios::setstate。这将允许调用者测试流,或者在为流启用异常的情况下,将引发异常。
您也无法检查流的状态。 C++ FAQ lite 有一个很棒的部分解释了这一点。为了澄清这一点,我添加了下面的代码片段。
You can set the flags of the stream to a state such as ios::bad or ios::fail using ios::setstate. This will allow the caller to test the stream or in the case that exceptions are enabled for the stream, an exception will be raised.
You also fail to check the state of your stream. The C++ FAQ lite has a great section explaining this. To clarify this I have added the code snippet below.