[英]Limiting input size with std::setw in std::cin
Let's say I have sample code: 假设我有示例代码:
std::string s;
std::cin >> std::setw(4) >> s;
std::cout << s;
Now for input abcdef
the result will be abc
and for abc
it will be abc
too. 现在输入
abcdef
的结果将是abc
,对于abc
它也将是abc
。 The question is how can I check whether the string was split in the middle due to the limit or the result string is the actual one? 问题是如何检查字符串是否由于限制而在中间分割,或者结果字符串是否为实际字符串? I need to know whether the input fits or some data was skipped.
我需要知道输入是否适合或是否跳过某些数据。
Although I know that the stream's width is considered when reading into a char*
I wasn't aware that it is also considered when reading into a std::string
. 虽然我知道在读入
char*
时我们会考虑流的宽度char*
我不知道在读入std::string
时也会考虑它。 Assuming it is, reading would stop under three conditions: 假设是,读取将在三个条件下停止:
eof()
is set. eof()
。 That is, you can check in.eof()
and std::isspace(in.peek()
. Well, is there is a funny std::ctype<char>
facet used by the stream you'd really need to use 也就是说,你可以检查
in.eof()
和std::isspace(in.peek()
。那么,你真正需要使用的流是否有一个有趣的std::ctype<char>
facet
std::isspace(in.getloc(),
std::char_traits<char>::to_char_type(in.peek()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.