0

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.

2
  • What happens if the user enter a string longer than 20 characters? Then you have buffer overflow. Use std::string and check its length. Commented May 22, 2014 at 19:33
  • @JoachimPileborg - I have to use char* according to the assignment Commented May 22, 2014 at 20:23

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

nice, but I had to add cin.ignore() and cin.clear();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.