Search code examples
c++ccstringc-strings

Knowing initial user input after getline cstring assignment


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


Solution

  • C-style terminated strings are rather tricky to work with, and in almost every case I'd recommend the C++ std::string instead. 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 for MAX characters followed by the terminator.

    istream::getline sets the streams failbit flag 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.

    while (!std::cin.getline(buffer, MAX+1)) {
        std::cout << "Too long\n";
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }