CIN在一定范围内

CIN within certain range

本文关键字:范围内 CIN      更新时间:2023-10-16

我正在尝试创建一个cin,其中用户只能输入0到1。如果用户没有输入这些数字,那么他应该会得到一个错误,说"请在0到1的范围内输入。"

但它不起作用。

我做错了什么?

   int alphaval = -1;
    do
    {
        std::cout << "Enter Alpha between [0, 1]:  ";
        while (!(std::cin >> alphaval)) // while the input is invalid
        {
            std::cin.clear(); // clear the fail bit
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n'); // ignore the invalid entry
            std::cout << "Invalid Entry!  Please Enter a valid value:  ";
        }
    }
    while (0 > alphaval || 1 < alphaval);
    Alpha = alphaval;

试试这个:

int alphaval;
cout << "Enter a number between 0 and 1: ";
cin >> alphaval;
while (alphaval < 0 || alphaval > 1)
{
        cout << "Invalid entry! Please enter a valid value: ";
        cin >> alphaval;
}

如果您想捕获空行,我会使用std::getline,然后分析字符串以查看输入是否有效。

类似这样的东西:

#include <iostream>
#include <sstream>
#include <string>
int main()
{
    int alphaval = -1;
    for(;;)
    {
        std::cout << "Enter Alpha between [0, 1]:  ";
        std::string line;
        std::getline(std::cin, line);
        if(!line.empty())
        {
            std::stringstream s(line);
            //If an int was parsed, the stream is now empty, and it fits the range break out of the loop.
            if(s >> alphaval && s.eof() && (alphaval >= 0 && alphaval <= 1))
            {
                break;
            }
        }
        std::cout << "Invalid Entry!n";
    }
    std::cout << "Alpha = " << alphaval << "n";
    return 0;
}

如果你想要一个不同的错误提示,那么我会把初始提示放在循环之外,然后把内部提示改为你喜欢的。

C++第一周,从Lynda.com上Peggy Fisher的学习C++开始。这就是我想到的。喜欢接受反馈。

int GetIntFromRange(int lower, int upper){
    //variable that we'll assign input to
    int input; 
    //clear any previous inputs so that we don't take anything from previous lines
    cin.clear(); 
    cin.ignore(numeric_limits<streamsize>::max(), 'n');
    //First error catch. If it's not an integer, don't even let it get to bounds control
    while(!(cin>>input)) {
        cout << "Wrong Input Type. Please try again.n";
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), 'n');
   }
    //Bounds control
    while(input < lower || input > upper) {
        cout << "Out of Range. Re-enter option: ";
        cin.ignore(numeric_limits<streamsize>::max(), 'n');
        //Second error catch. If out of range integer was entered, and then a non-integer this second one shall catch it
        while(!(cin>>input)) {
            cout << "Wrong Input Type. Please try again.n";
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), 'n');
        }
    }
    //return the cin input
    return input;
}

由于练习是点汉堡,所以我是这样要求金额的:

int main(){
    amount=GetIntFromRange(0,20);
}