user3155478
user3155478

Reputation: 1055

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.

Upvotes: 0

Views: 124

Answers (1)

David G
David G

Reputation: 96845

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.

Upvotes: 1

Related Questions