c++ - while (cin>> struct str) 在 C++ 中我该如何使用?

标签 c++

我在将 while(cin) 与结构一起使用时遇到了麻烦。有人可以让我清楚这个问题吗?不知道有没有人问过这种帖子。如果是,请原谅我和我糟糕的英语。

struct ThiSinh{
     string m_HT;
     float m_H;
};

我为它重载了运算符>>

bool operator >> (istream& is, ThiSinh &ts){
    getline(is, ts.m_HT);
    is >> ts.m_H;
    is.ignore();
    return ???;
}

因为 while (cin >> ThiSinh) 需要一个 bool 类型,所以我不知道它应该返回什么数字或数据。以及如何在我按下 ctrl + Z 时打破 while 循环。 我也试过了

while(cin){
   ThiSinh ts;
   cin >> ts;
}

它起作用了,但我不想得到那个虚假数据。所以有人请帮助我。提前致谢。

最佳答案

您的 operator >> 返回一个 bool,这对于流提取运算符来说是非常不寻常的,并使其在大多数流上下文中无法使用。此类运算符应返回对其进行运算的流的引用:

istream& operator >> (istream& is, ThiSinh &ts){
    getline(is, ts.m_HT);
    is >> ts.m_H;
    is.ignore();
    return is;
}

这就是多重​​提取的实际工作方式:

std::cin >> a >> b >> c;

实际上,这首先执行 auto &tmp = operator>>(std::cin, a),然后调用 operator>>(tmp, b),然后等等。

之所以可以在条件中使用流(以及扩展的流提取操作)是因为std::istream(和std::ostream)定义了一个转换为 bool(如果流处于无错误状态,则返回 true);然后由条件调用该转换。

换句话说,这:

while (std::cin >> ts)

实际上变成了这样:

while (static_cast<bool>(operator>>(std::cin, ts)))

并且转换是可能的,因为 operator>> 返回 std::istream& 并且 std::istream 定义了到 的转换 bool

关于c++ - while (cin>> struct str) 在 C++ 中我该如何使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47848822/

相关文章:

c++ - 嵌套调用中的数组运算符 (->) 重载

android - 当我从 native 代码将非 nullptr 传递给 `alBufferData()` 时,OpenAL 应用程序崩溃/挂起

python - 嵌入式 Python 找不到某些模块,(ctypes,...)

c++ - isSet() 或 operator void*() 或 explicit operator bool() 或其他?

c++ - 异步函数调用的参数生命周期

c++ - 如何从十六进制字符串中获取小数

c++ - 从 char* 数组中读取 "integer"大小的字节。

c++ - 工厂方法 C++ 实现

c++ - Ubuntu Conda环境下无法编译R包: x86_64-conda-linux-gnu-c++: not found

C++ - 为模板类专门化成员函数