raz
raz

Reputation: 128

C++ code loop issue

I have the following code that prompts the user to enter a code that contains only numbers. If the user enters two times an invalid code, the program goes further without a valid code.

int main()
{
    char code[10];
    cout << "Enter the code: ";
    cin >> code;

    int codeLength = strlen(code);
    int i = 0;
    while (code[i] >= '0' && code[i] <= '9')
        i++;

    if (i != codeLength)
    {
        cout << "The code is not valid: " << codDat << endl;
        cout << "Enter the code again: ";
        cin >> code;
    }

    cout << code <<endl;
    return 0;
}

How can I prompt the user to enter a new code until the entered code contains only numbers? I’ve already tried this:

do {
    cout << "Enter the code again: ";
   cin >> code;
} while (code[i] >= '0' && code[i] <= '9');

This code only checks the first character, but I can’t figure out how to make the right loop.

Upvotes: 1

Views: 111

Answers (2)

paper.plane
paper.plane

Reputation: 1197

Try by modifying your code as below.

while(true)
{
    i=0;

    while(i<codeLength && code[i] >= '0' && code[i] <= '9')
        i++;

    if(i != codeLength)
    {
        cout << "The code is not valid: " << codDat << endl;
        cout << "Enter the code again: ";
        cin >> code;
    }
    else
        break;
}

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234875

I'd be inclined to read a std::string:

std::string foo;
cin >> foo;

Then use

bool is_only_digits = std::all_of(foo.begin(), foo.end(), ::isdigit);

to check if the input contains only numbers. (You can also use foo.size() to check the string length).

This will be much easier to fashion into a loop.

Upvotes: 5

Related Questions