basic_istream::sentry
描述 (Description)
它用于准备输入流。 执行输入操作的所有成员函数自动构造此类的对象,然后对其进行求值(如果未设置状态标志,则返回true)。 仅当此对象的计算结果为true时,该函数才会尝试输入操作(否则,它将返回而不执行它)。 在返回之前,该函数会破坏sentry对象。
声明 (Declaration)
以下是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;
};
成员 (Members)
explicit sentry (basic_istream& is, bool noskipws = false); - 为输出操作准备输出流,执行上述操作。
~sentry(); - 不执行任何操作(实现定义)。
explicit operator bool() const; - 评估对象时,它返回一个bool值,指示iftry构造函数是否成功执行了所有任务:如果在构造过程的某个时刻设置了内部错误标志,则此函数始终为该对象返回false。
例子 (Example)
在下面的例子中解释了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