Here’s a C++ function of mine:
void SetUserName(char username[])
{
cout << "\nPlease enter a username.\n"
<< "Must not be longer than 12 characters.\n>> ";
cin.getline(username, MAX) // MAX is globally defined
while(strlen(username) > MAX)
{
cout << "\nUsername too long, try again.\n>> ";
cin.getline(username, MAX);
}
}
Obviously, the while loop never works because the user input is truncated to 12 characters everytime.
How can I effectively determine if the user input was too long, and continue to loop until the conditions are met?
Edit: Using cstring here is a requirement. I already know how easy it is with strings.
Edit #2: This was definitely a fruitful question for me, as it taught me a lot. Final code: http://pastie.org/3537894
C-style terminated strings are rather tricky to work with, and in almost every case I’d recommend the C++
std::stringinstead. However, since you say you specifically want to read a terminated string into an array, here is one way to do it.Remember that the array size must be
MAX+1, so there’s space forMAXcharacters followed by the terminator.istream::getlinesets the streamsfailbitflag if the line is too long; you can test this after reading. If only a partial line was extracted, and you want to move on to the next line, then you’ll need to clear the error state, and ignore the rest of the line.