Rosario Monroy
Rosario Monroy

Reputation: 21

Validate input data in an array C++

I have this program that i took it out from: https://intcpp.tech-academy.co.uk/input-validation/ and it works fine, i did some changes because i need the program to keep asking the user to enter a valid input, so that why it has the while in there however it only asks 4 times after that 4th time the input will be valid it does not matter if it right or not, Does any one know how i can fix this. Thank you

#include <iostream>
#include <string>
#include <cctype>

using namespace std;

int main () {

    cout << "Please enter name:" << endl;
    string userName;
    getline(cin, userName);

    bool rejected = false;

    while (rejected == false)
    {
        for (unsigned int i = 0; i < userName.length() && !rejected; i++)
        {

            if (isalpha(userName[i]))
                continue;

            else if (userName[i] == ' ')
                continue;

            else
            {
                cout << "Error, Please enter Patient's name again, First Name: ";
                getline(cin, userName);
                rejected = false;
            }

        }
        rejected = true;
    }

    system("pause");
    return 0;
}

Upvotes: 0

Views: 524

Answers (2)

L&#234; Tuấn Anh
L&#234; Tuấn Anh

Reputation: 1

    if (isalpha(userName[i]) || (userName[i] == ' '))
        continue;
    else
    {
        cout << "Error, Please enter Patient's name again, First Name: ";
        getline(cin, userName);
        i = -1; //Reset check name
    }

Try it! Change unsigned int to int

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409196

Personally I would do something like

bool is_valid_username(std::string const& username)
{
    // First trim the string of all leading and trailing white-space
    trim(username);

    if (username.length() == 0)
        return false;  // Input was empty or all spaces

    return std::all_of(begin(username), end(username), [](char const ch)
    {
        return std::isalpha(ch) || ch == ' '; // Only letters and spaces are allowed
    });
}

std::string get_username()
{
    std::string username;

    do
    {
        std::cout << "Please enter username: ";
        std::getline(std::cin, username);
    } while (!is_valid_username(username));

    return username;
}

[For the trim function please see this old answer]

The get_username function will continue to ask for a username forever if the input is either empty, all spaces, or contains non-letters or not a space.

Here's a reference for std::all_of.

Here's a reference about lambda expressions.

Upvotes: 1

Related Questions