0
我在使用cin.peek
進行驗證時遇到了問題。 我想要做的只是從用戶獲得積極的int
。我使用下面的代碼 (我不得不使用功能) 嘗試(getwholenum
和getposnum
做工精細沒有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;
}
_「我有麻煩......「很含糊。你可以請更具體嗎? –
對不起,這是我在這裏的第一個問題 – Moya
所以我想驗證整個積極int,但是當我不把一封信沒有什麼會發生 – Moya