2016-12-07 230 views
0

我在使用cin.peek进行验证时遇到了问题。 我想要做的只是从用户获得积极的int。我使用下面的代码 (我不得不使用功能) 尝试(getwholenumgetposnum做工精细没有getnum功能):cin.peek输入验证

#include <iostream> 
#include <string> 

using namespace std; 


double getposnum(double &); //function protoype for getting positive number 
double getwholenum(double &); //function protoype for getting a whole number 
double getnum(double &);  //function protoype for getting an int 

int main() 
{ 




static double x; 
cout << "please give me a number" << endl; 
cin >> x; 
cin.ignore(); 
x = getnum(x); 
cout << x; 
cin.get(); 

} 

double getnum(static double & x) //validation for int only (no char) 
{ 
// cin checks if the stream has failed 
// cin = true, cin = false !cin 


while (!(cin >> x)) 
{ 
    cout << "Input was not a number" << endl << "Enter a VALID number! "; 
    cin >> x; 
    cin.clear(); 
    cin.ignore(); 

} 
cout << "it's not a letter"; 
getposnum(x); 

return x; 
} // if i dont put in a letter nothing would happen 


double getposnum(static double & x) // another function to get a positive number 
{ 
while (x < 0) 
{ 
    cout << "negative" << endl; 
    cin >> x; 
    cin.ignore(); 

} 
cout << "positive" << endl; 

getwholenum(x); 

return x; 
} 

double getwholenum(static double & x) 
{ 
while (x != static_cast<int>(x)) // forcing a double into an int if it's equal then the number was an in 
{ 
    cout << "not a whole number" << endl; 
    cin >> x; 
    cin.ignore(); 
} 
cout << "whole number"; 
return x; 
}  
+0

_“我有麻烦......“很含糊。你可以请更具体吗? –

+0

对不起,这是我在这里的第一个问题 – Moya

+0

所以我想验证整个积极int,但是当我不把一封信没有什么会发生 – Moya

回答

0

尝试......

include <iostream> 
using namespace std; 

int main() 
{ 
    int num; 
    cout << "Enter a positive integer: "; 
    cin >> num; 

    while (num <= 0 || cin.peek() != '\n') 
    { 
     cout << "Invalid Input!\n"; 
     cin.clear(); 
     cin.ignore(numeric_limits<streamsize>::max(), '\n'); 
     cout << "Please re-enter [positive integer only]: "; 
     cin >> num; 
    } 

    return 0; 
}