C++:只允许数字作为输入

C++: Just allow numbers as an input

我想在下面的代码中屏蔽所有的输入字母,你能帮我吗?

#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{
...

程序的其余部分只是数学。

当您声明一个变量的类型时,该变量不能包含您声明的内容以外的任何内容。所以:你不能使用 int m 来输入浮点数。但是,您可以使用 cin.ignore() (more details here) 接受用户输入的“4.1”作为“4”。给你:

#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;        
}