Search code examples
c++while-loopcincoutostream

Is this a good practice to check user input?


do {
    std::cout << "Enter a valid name" << std::endl;
    std::cin >> name;

} while (!validName(name) && std::cout << "It is not a valid name" << std::endl);

Is this a good practice tha if the name is not valid, then I respond with a line this way?


Solution

  • It's probably clearer to do the checking and output within the loop itself. You can do this by breaking an infinite loop or continuing a one-time loop. For example:

    do {
        std::cout << "Enter a valid name" << std::endl;
        std::cin >> name;
        if (!validName(name)) {
            std::cout << "It is not a valid name" << std::endl;
            continue;
        }
    } while (false);
    

    Or the reverse:

    for ( ;; ) {
        std::cout << "Enter a valid name" << std::endl;
        std::cin >> name;
        if (validName(name))
            break;
    
        std::cout << "It is not a valid name" << std::endl;
    }
    

    I generally prefer the second, since it makes it easy to inject a counter, so you can do some other type of error handling if the loop body fails more than a certain number of times.

    for (int attempt = 0; attempt < 3; ++attempt) {
        std::cout << "Enter a valid name" << std::endl;
        std::cin >> name;
        if (validName(name))
            break;
    
        std::cout << "It is not a valid name" << std::endl;
    }
    
    if (!validName(name)) {
        std::cout << "Failed to get a valid name after 3 tries" << std::endl;
        std::abort();
    }