简体   繁体   English

使用std :: cin中的std :: setw限制输入大小

[英]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: 假设是,读取将在三个条件下停止:

  1. The stream is completely read in which case eof() is set. 完全读取流,在这种情况下设置eof()
  2. The next character is a space. 下一个字符是一个空格。
  3. The number of characters which need to be read are read. 读取需要读取的字符数。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM