繁体   English   中英

对出站字符数组进行错误检查-使用std :: cin

[英]Error-checking for outbounded char-Array - using std::cin

使用std :: cin时如何对出字符长度进行错误检查?

char _charArr[21];
bool inputNotVerified = true;
while (inputNotVerified) {
     cout << "input a string no more than 20 chars: ";
     cin >> _charArr;  
 // if the errorchecking works the boolean should be set to false 
}

如上面的评论所述-唯一会破坏循环的事情是输入正确时-最多20个字符。 但是我该如何实施呢?

我试图使条件超出strlen(_charArr),但没有成功。

使用std::istream::getline()

if (std::cin.getline(_charArr, sizeof _charArr) && std::cin.gcount()) {
    // ...
}

std::istream::getline()将仅读取第二个参数提供的最大count字符。 gcount()用于检查是否已读取至少一个字符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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