有没有办法让iostream对布尔值有更严格的要求?
我使用std::boolalpha得到了意想不到的结果
bool var;
std::istringstream is("true1");
is >> std::boolalpha >> var;生成var == true、is.good() == 1和is.peek() == '1',而我期望的是is.good() == 0。
未指定boolalpha时的类似行为:
bool var;
std::istringstream is("1qwe");
is >> var;生成var == true、is.good() == 1和is.peek() == 'q',而我期望的是is.good() == 0。
发布于 2021-05-17 16:32:34
不,没有办法以这种方式使iostream更加严格。
也没有必要这样做。例如,只需使用is.peek()检查是否使用了整个输入。如果不是,则将输入视为错误,然后重试(或者在case is.good() == 0中执行任何您想做的操作)。
发布于 2021-05-17 16:54:00
所有格式化输入函数在成功读取项目后停止,并在该项目结束后立即设置位置(在下一个字符上)。
您可以只测试peek是否返回特征::eof():
if (is.peek() != std::istringstream::traits_type::eof()) {
// invalid input
...
}发布于 2021-05-17 17:32:08
您不能使流更严格,但您可以定义一个更“严格”流的包装类。
以下内容(对流状态管理的正确性持保留意见):
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;
}
}https://stackoverflow.com/questions/67566228
复制相似问题