问题描述
#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;
}