简体   繁体   中英

Error-checking for outbounded char-Array - using std::cin

How can I make an error checking of outbounding the charlength when using 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 
}

As stated in the comment above - the only thing that can break the loop is when the input is correct - that is no more than 20 characters. But how do i implement it?

I have tried to make a condition out of strlen(_charArr) but without success.

Use std::istream::getline() :

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

std::istream::getline() will only read a maximum of count characters which is provided by the second argument. gcount() is for checking if at least one character has been read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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