【问题标题】:cin.peek for input validationcin.peek 用于输入验证
【发布时间】:2017-04-22 13:42:15
【问题描述】:

我在使用 cin.peek 进行验证时遇到问题。 我想要做的是只从用户那里得到一个积极的int。我试过使用下面的代码 (我必须使用函数) (getwholenumgetposnum 在没有 getnum 功能的情况下工作正常):

#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 您希望在哪里使用cin.peek()

标签: c++ validation input int


【解决方案1】:

试试这个...

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-11
    • 2011-08-09
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    • 2017-12-17
    • 2018-04-13
    相关资源
    最近更新 更多