2022-06-23

Why does cin.fail() ignore periods and commas in "while" loop? What's a simple way to error check input?

Sorry it sounds stupid, but I'm just getting started in C++ programming...
My input checking loop works fine if I want it to accept 'float' numbers, but outputs some weird results if it has to accept only 'int' numbers.
EDIT: Tutorials I read/watched assumed that user wouldn't input things like that, which is dumb...

#include <iostream>
#include <limits>
using namespace std;

// input with check
int num(int i) {
    int x=0;
    cout<<"Enter #"<<i+1<<": ";
    cin>>x;
    while(cin.fail()) {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(),'\n');
        cout<<"Enter INTEGER #"<<i+1<<": ";
        cin>>x;
    }
    return x;
}

int main() 
{
    int i, min=0, max=0, n=3;
    int arr[3];

    // save input into array
    for(i=0; i<n; i++) { arr[i] = num(i); }
    
    // find 'max' & 'min'
    max = arr[0];
    for(i=1; i<n; i++) {
        if(max < arr[i]) { max = arr[i]; }
    }
    min = arr[0];
    for(i=1; i<n; i++) {
        if(min > arr[i]) { min = arr[i]; }
    }
    cout << endl << "MAX = " << max;
    cout << endl << "MIN = " << min;
    return 0;
}


For example if I type in 5.2 it takes in the 5, skips one loop and puts out error message on the next loop.
Output:
Enter #1: 2
Enter #2: 5.5
Enter #3: Enter INTEGER #3: g
Enter INTEGER #3: -2
MAX = 5
MIN = -2

EDIT2: I did some digging and I found something that kind of works for my use and is simple enough for my skill level, but still has some quirks. Function just filters out anything that isn't characters you specify between the quotes and checks if '-' is as the first character.

bool isNumeric(string const &str) {
    if(str.find_last_of("-")==0 || str.find_last_of("-")==SIZE_MAX) {
        return !str.empty() && str.find_first_not_of("-0123456789") == string::npos;
    } else { return 0; }
}
int num(int i) {
    string str;
    cout << "Enter #" << i+1 << ": ";
    getline(cin,str);
    while(isNumeric(str)==0) {
        cout << "Enter INTEGER #" << i+1 << ": ";
        getline(cin,str);
    }
    return stoi(str); // convert string to integer
}

Source: https://www.techiedelight.com/determine-if-a-string-is-numeric-in-cpp/ - method #3



No comments:

Post a Comment