0

I have the following code:

#include <iostream>
#include <limits>
#include <locale>

using namespace std;

int main(int argc, char** argv) {

    setlocale(LC_ALL, "English");

    int i, vetor[16];
    for(i = 0; i < 16; i ++) {
        cout << "Input the position: [" << i << "]: ";
        cin  >> vetor[i];
        if(cin.fail()) {
            cin.clear();
            cin.ignore(numeric_limits < streamsize > ::max(), '\n');
            cout << "Please, input only numbers." << endl;
            i --;
            continue;
        }

        if(vetor[i] <= 0) {
            cout << "Insert a non-zero value." << endl;
            i --;
            continue;
        }
    }
    cout << vetor[0];

    return 0;
}

And I need to accept only numbers. When I run it and insert "1" (or any other number), it goes to the following position, what's correct. When I input "a", it shows me the error and warn me to input only numbers, what's correct too. If I input "a1", the same thing occurs, what's correct. But when I input "1a", it shows me the warning, but the code continues to the next position, and when it executes the last line with the cout command above the return, it tells me the value is "1", not "1a", because the type of the variable is int I believe.

Can someone tells me why does it happen? I need to accept only numbers, and "1a" is not a number. How can I filter this and how can I do to when I input "1a", occurs the same thing as I had input "a"?

I use DevC++ 5.11.

Edie Johnny
  • 513
  • 2
  • 5
  • 14

1 Answers1

1

It happens because cin extracts the 1 digit in one pass, and stores that in your array. It stops reading when it encounters the a (since that is not a valid character for an integer), and leaves it in the input buffer. It then reads the a on the next pass, which causes it to fail because it's not an integer.

What you should do is use std::getline to read strings instead. Then you can do any kind of parsing you want. You can use functions from the standard library like std::stoi if they suit you. Otherwise write your own custom parsing.

Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274