C++ 使iostreams更加严格
有没有办法让iostreams对带有某个标志的布尔值更加严格 我使用std::boolalpha得到了意想不到的结果 布尔变量; std::istringstream istrue1; is>>std::boolalpha>>var; 当我期望is.good==0时,产生var==true、is.good==1和is.peek==1 未指定boolalpha时的类似行为: 布尔变量; std::istringstream是1qwe; is>>var;C++ 使iostreams更加严格,c++,C++,有没有办法让iostreams对带有某个标志的布尔值更加严格 我使用std::boolalpha得到了意想不到的结果 布尔变量; std::istringstream istrue1; is>>std::boolalpha>>var; 当我期望is.good==0时,产生var==true、is.good==1和is.peek==1 未指定boolalpha时的类似行为: 布尔变量; std::istringstream是1qwe; is>>var; 当我期望is.good==0时,产生var=
当我期望is.good==0时,产生var==true、is.good==1和is.peek==q。不,没有办法以这种方式使iostreams更严格
也没有必要。例如,只需使用is.peek来检查是否使用了整个输入。如果不是,则将输入视为坏输入,然后重试,或者在case is.good==0时执行任何您想执行的操作。否,没有办法通过这种方式使iostreams更严格
也没有必要。例如,只需使用is.peek来检查是否使用了整个输入。如果不是,则将输入视为坏输入,然后重试,或者在case is.good==0的情况下执行任何操作。所有格式化输入函数在成功读取项目后停止,并在该项目结束后的下一个字符上设置其位置 您可以测试peek返回的Traits::eof:
if (is.peek() != std::istringstream::traits_type::eof()) {
// invalid input
...
}
所有格式化输入函数在成功读取项目后停止,并在该项目结束后的下一个字符上设置其位置 您可以测试peek返回的Traits::eof:
if (is.peek() != std::istringstream::traits_type::eof()) {
// invalid input
...
}
不能使流更严格,但可以定义一个更严格地流的包装类。 以下内容对流状态管理的正确性有所保留:
template<typename T>
class stricter_io
{
public:
explicit stricter_io(T& t) : t(t) {}
friend std::istream& operator>>(std::istream& is, stricter_io<T>&& val)
{
auto pos = is.tellg();
if (is >> val.t)
{
// Whatever condition you want;
// this examples requires either eof or whitespace after the item.
auto next = is.peek();
if (next != std::istringstream::traits_type::eof()
&& !std::isspace(next))
{
// Rewind the stream and enter the failure state.
is.seekg(pos);
is.setstate(std::ios_base::failbit);
}
}
return is;
}
private:
T& t;
};
int main()
{
bool var;
std::istringstream is("true1");
if (is >> std::boolalpha >> stricter_io(var))
{
std::cout << "Good";
}
else
{
std::cout << "Bad\n";
is.clear();
std::string s;
is >> s;
std::cout << s << std::endl;
}
}
不能使流更严格,但可以定义一个更严格地流的包装类。 以下内容对流状态管理的正确性有所保留:
template<typename T>
class stricter_io
{
public:
explicit stricter_io(T& t) : t(t) {}
friend std::istream& operator>>(std::istream& is, stricter_io<T>&& val)
{
auto pos = is.tellg();
if (is >> val.t)
{
// Whatever condition you want;
// this examples requires either eof or whitespace after the item.
auto next = is.peek();
if (next != std::istringstream::traits_type::eof()
&& !std::isspace(next))
{
// Rewind the stream and enter the failure state.
is.seekg(pos);
is.setstate(std::ios_base::failbit);
}
}
return is;
}
private:
T& t;
};
int main()
{
bool var;
std::istringstream is("true1");
if (is >> std::boolalpha >> stricter_io(var))
{
std::cout << "Good";
}
else
{
std::cout << "Bad\n";
is.clear();
std::string s;
is >> s;
std::cout << s << std::endl;
}
}
这并不是说iostream应该更严格,而是作为程序员,您应该编写严格满足您需要的代码。如果你想让1qwe在读取时失败,那么你应该为它编写逻辑。不是说iostream应该更严格,而是作为程序员,你应该编写严格满足你需要的代码。如果您希望1qwe在读取时失败,那么您应该为其编写逻辑。