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

时间:2016-07-21 16:42:34

标签: c++ input

我试图让程序只接受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;
}

2 个答案:

答案 0 :(得分:1)

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

让我们使用one of those few,是吗?

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 == '\0') // 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.
}

答案 1 :(得分:0)

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

var obj = {val: 5};

function changeVal( param ) {
 param.val = param.val  + 5;
 return param.val ;
}
console.log(obj.val) // 5
console.log(changeVal(obj)) // 10
console.log(obj.val) // 10

第一个基本上是说,如果流(控制台输入)确实失败或下一个流char(.peek())不是\ r或\ n,则清除流并获取第一个字符。< / p>

虽然该char不是\ n而不是文件结束(EOF),然后获取下一个字符,依此类推。

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

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

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

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

注意:调用函数如下:

       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
    }