C++ Istream 库 - sentry
描述
它用于为输入准备流。 所有执行输入操作的成员函数都会自动构造此类的对象,然后对其求值(如果未设置状态标志,则返回 true)。只有当这个对象的计算结果为真时,函数才会尝试输入操作(否则,它会返回而不执行它)。 在返回之前,该函数销毁哨兵对象。
声明
以下是 std::basic_istream::sentry 的声明。
C++98
class sentry {
public:
explicit sentry (basic_istream& is, bool noskipws = false);
~sentry();
operator bool() const;
private:
sentry (const sentry&);
sentry& operator= (const sentry&);
};
C++11
class sentry {
public:
explicit sentry (basic_istream& is, bool noskipws = false);
~sentry();
explicit operator bool() const;
sentry (const sentry&) = delete;
sentry& operator= (const sentry&) = delete;
};
成员
explicit sentry (basic_istream& is, bool noskipws = false); − 为输出操作准备输出流,执行上述操作。
~sentry(); − 不执行任何操作(实现定义)。
explicit operator bool() const; − 评估对象时,它返回一个布尔值,指示哨兵构造函数是否成功执行其所有任务:如果在构造过程的某个时刻设置了内部错误标志,则此函数始终为该对象返回 false。
示例
在下面的例子中解释了 std::basic_istream::sentry。
#include <iostream>
#include <string>
#include <sstream>
#include <locale>
struct Phone {
std::string digits;
};
std::istream& operator>>(std::istream& is, Phone& tel) {
std::istream::sentry s(is);
if (s) while (is.good()) {
char c = is.get();
if (std::isspace(c,is.getloc())) break;
if (std::isdigit(c,is.getloc())) tel.digits+=c;
}
return is;
}
int main () {
std::stringstream parseme (" (555)2326");
Phone myphone;
parseme >> myphone;
std::cout << "digits parsed: " << myphone.digits << '\n';
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 −
digits parsed: 5552326

