dimanche 13 septembre 2020

C++: 'if-else' and 'switch' is broken [closed]

My program needs to check if an inserted string is a natural number without anything mixed in-between before any further actions can be done. For this reason, I made a filter inside a 'for' loop to check if all inserted characters are actually numbers, but the app seemingly skips over every check, and immediately goes to the reinsertion part.

I have tried doing this with both the 'switch' and 'if-else', but both of them seem to have this problem. Below are the code snippets that should better show what I mean.

The 'if-else' code:

using namespace std;

int main (){
    string in;
    cout << "Insert your string: ";
    getline (cin, in);
    int l = in.size(), x = 5;
    for (int i = 0; i < l;) {
        if (in[i] == 0 || in[i] == 1 || in[i] == 2 || in[i] == 3 || in[i] == 4 || in[i] == 5 || in[i] == 6 || in[i] == 7 || in[i] == 8 || in[i] == 9){
            i++;
        }
        else {
            cout << "This is not a valid number.";
            cout << "\nPlease try again: ";
            getline (cin, in);
            l = in.size();
            i = 0;
        }
    }
    cout << "The string is a valid number."
    return 0;
}

The 'switch' code:

using namespace std;

int main (){
    string in;
    cout << "Insert your string: ";
    getline (cin, in);
    int l = in.size(), x = 5;
    for (int i = 0; i < l;) {
        switch (in[i]){
            case 0:
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
            case 8:
            case 9:
                i++;
                break;
            default:
                cout << "This is not a valid number.";
                cout << "\nPlease try again: ";
                getline (cin, in);
                l = in.size();
                i = 0;
                break;
        }
    }
    cout << "The string is a valid number.";
    return 0;
}

Can you help me fix this problem, or maybe suggest a better way to filter out valid data?

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire