0

I want to block all the letters for input in the following code, can you help me with that?

#include <iostream>
using namespace std;

int main()
{
cout<<"To close this program you need to type in -1 for the first input"<<endl;
int m, n;
do{

 int counter1 = 0;
 int counter2 = 0;
 cout<<"Now you need to input two seperate natural numbers, and after that it calculates the difference of both numbers factors!"<<endl;

 cout<<"First Input"<<endl;
 cin>>m;
 if(m==-1){
    break;
 }
 cout<<"Second Input"<<endl;
 cin>>n;
if(m<0 or n<0){
    cout<<"ERROR - Only natural numbers are allowed!"<<endl;
}
else{
...

The rest of the program is just the math.

David
  • 5
  • 3

1 Answers1

0

When you declare a type of a variable, the variable can't contain anything else than what you have declared. So: You can’t use an int m to input a float. You could however use cin.ignore() (more details here) to accept a user input of "4.1" as "4". Here you go:

#include <iostream>
#include <limits>

using namespace std;

int main() {
    cout << "Enter an int: ";

    int m = 0;
    while(!(cin >> m)) {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "Invalid input!\nEnter an int: ";
    }

    cout << "You enterd: " << m << endl;        
}
Alex
  • 36
  • 5