C++用户输入浮点值而不是整数

C++ user enters floating point instead of integer

本文关键字:整数 用户 输入 C++      更新时间:2023-10-16

我试图让程序只接受x作为整数,然后要求另一个整数y。然而,当我在x中输入浮点时,它会取输入的小数部分,并使其成为y值。我不确定我在这里犯了什么错误。

#include <iostream>
#include <string>
#include <limits>
using namespace std;
int getInt()
{
    int x = 0;
    while (!(cin >> x))
    {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), 'n');
        cout << "Please input a proper 'whole' number: " << endl;
    }
    return (x);
}
int toobig()
{
    cout << "Your number is too large, please enter something smaller: " << endl;
    int x = getInt();
    return (x);
}
int toosmall()
{
    cout << "your number is negative, please enter a positive number: " << endl;
    int x = getInt();
    return (x);
}

int main()
{
    cout << "your number please:-" << endl;
    int x = getInt();
    if (x>100000)
    {
        toobig();
    }
    else if (x<0)
    {
        toosmall();
    }
    int y = 0;
    cout << "enter y " << endl;
    cin >> y;
    cout << "x = " << x << endl;
    cout << "y = " << y << endl;
    system("PAUSE");
    return 0;
}

大多数到int的转换在发现不能成为int的一部分时就会停止,只有少数转换函数会告诉您它们是否在解析整个字符串之前停止。

让我们用其中一个,好吗?

int getInt()
{
    for ( ; ; ) // loop until user provides something we can use. 
                // This is dangerous. You probably want to give up after a while.
    {
        std::string input; // read in as string
        if (std::cin >> input)
        {
            char * endp; // will be updated with pointer to where conversion stopped
            errno = 0;
            // convert string to int
            long rval  = std::strtol (input.c_str(), &endp, 10); 
            if (*endp == '') // check whole string was read
            {
                if (errno != ERANGE) // check converted number did not overflow long
                {
                    if (rval >= std::numeric_limits<int>::min() &&
                        rval <= std::numeric_limits<int>::max())
                         // check converted number did not overflow int
                         // you could replace this min and max with your own passed-in 
                         // min and max values if you want
                    {
                        return rval; // return the known-to-be-good int
                    }
                }
            }
        }
        else
        { // note: usually when cin fails to read a string, it's over. 
          // This is actually a good time to throw an exception because this 
          // just shouldn't happen.
            std::cin.clear(); // but for now we'll just clear the error and 
                              // probably enter an infinite loop of failure
        }
        // failed for any reason. Blow off all user input and re-prompt
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
        std::cout << "Please input a proper 'whole' number: " << std::endl;
    }
    return 0; // to satisfy compiler because a non-void function must always return. 
              // Never reached because of infinite for loop.
}

由于C++上的每个控制台输入都被视为字符串,因此在您的getInt()方法下,我将执行以下操作:

       int GetInt(istream &stream)
       {
        char obtainChar; //read a character from input   
        int x;    
        stream >> x;  
        while(stream.fail() || (stream.peek() != 'r' && stream.peek() != 'n'))
        {
            stream.clear(); //clear the fail state of stream
            obtainChar = stream.get(); //read a character from input
            while(obtainChar != 'n' && obtainChar != EOF) //while gotten char is not a return key or EOF
                obtainChar = stream.get(); //read a character from input iterate up to 'n' or EOF
            //displays an error message if there was a bad input (e.g. decimal value)
            cerr << endl << "Please input a proper 'whole' number: " << endl;
            cout << endl << "Please re-enter x: "; //re-prompt to re-enter a value
             x = GetInt(stream); //Try again by calling the function again (recursion)
        }
            return x; //will return after the user enters ONLY if an integer was inputted
    }

第一个while基本上是说,如果流(控制台输入)失败,或者下一个流char(.peek())不是a或a,则清除流并获取第一个字符。

如果该字符不是文件结尾(EOF),则获取下一个字符,依此类推。

如果出现问题,则向用户显示错误消息,并重新提示用户x的值。

然后调用相同的函数重新测试输入(递归),如果一切正常,则返回x的值。

现在可以调用此函数来评估Y.的值

注:istream是iostream库的一部分,基本上是cin

注意:调用函数如下:

int x;
cout << "your number please:-" << endl;
x = GetInt(cin);