C++ user input restriction with proper retry without “goto”

前端 未结 5 688
Happy的楠姐
Happy的楠姐 2021-01-15 14:01

I have the following code:

qstn:
  cout << \"Input customer\'s lastname: \";
  getline(cin, lname);

  if (lname.find_first_not_of(\"abcdefghijklmnopqr         


        
5条回答
  •  北海茫月
    2021-01-15 14:14

    It seems to me that your code suffers from lack of clarity of purpose.

    You apparently don't want the string that's entered to include a leading space, nor multiple consecutive spaces. Other than that, only alphabetic characters should be accepted.

    If the user does enter multiple consecutive spaces, I'd probably just ignore all but the first. I'd probably write the code something like this:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    bool non_alpha(std::string const &s) {
        return !std::all_of(s.begin(), s.end(), [](unsigned char c) { return std::isalpha(c) || std::isspace(c); });
    }
    
    std::string get_name(std::string const &prompt) {
        std::string result;
        std::string line;
    
        do {
            std::cout << prompt;
            std::getline(std::cin, line);
        } while (non_alpha(line));
    
        std::istringstream words(line);
        std::string word;
        while (words >> word)
            result += word + ' ';
        return result;
    }
    
    int main() {
        auto res = get_name("Please enter last name, alpha-only\n");
        if (res.empty())
            std::cout << "Oh well, maybe some other time";
        else
            std::cout << "Thanks Mr(s). " << res << "\n";
    }
    

    I'd be tempted to consider doing roughly the same for non-alphabetic characters--rather than asking the user to re-enter from the beginning, assume it's a mistake and just ignore it.

提交回复
热议问题