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.