cin将字符串的开头分配给int,仅在第二次调用中失败 [英] cin assigns beginning of string to int, only fails in second call

查看:51
本文介绍了cin将字符串的开头分配给int,仅在第二次调用中失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在代码段中

for(;;) {

    std::cout << "Please enter an integer: ";
    if(std::cin >> nInput) {
        return nInput;
    }
    else {
        std::cout << "Invalid input! Please enter an integer!\n";
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }

}

如果至少第一个字符为数字,

cin会将字符串的开头分配给nInput.例如,这是我的一些控制台输出:

cin will assign the beginning of a string to nInput, provided at least the first character is numeric. For instance, here's some of my console output:

Please enter an integer: 10
Please enter an integer: foo
Invalid input! Please enter an integer!
Please enter an integer: 20bar                                       //this will return 20, leave "bar" in the stream. Until the next cin call, cin.good() returns true
Please enter an integer: Invalid input! Please enter an integer!     //fails because "bar is in the stream"
Please enter an integer: -1

当用户输入"20bar"时,如何检查防止cin返回"20"?或者,如何检查cin缓冲区中是否有更多内容?

How do I check keep cin from returning "20" when the user inputs "20bar"? Alternatively, how can I check for more content in the cin buffer?

推荐答案

在这种情况下,您应该将数据读入std::string,然后检查字符串以查看是否具有有效的输入. cin >>非常满意20anything_here作为整数类型的输入,因为一旦找到非整数部分,它就会停止读取.

In situations like this you should read the data into a std::string and then check the string to see if you have valid input. cin >> is perfectly happy with 20anything_here as input for an integer type as it just stops reading once it finds the non integer part.

一旦解析了字符串并确定它满足您的要求,就可以使用 std::stoi 将字符串转换为int

Once you parse the string and determine that it meets your requirements you can use std::stoi to convert the string to an int

这篇关于cin将字符串的开头分配给int,仅在第二次调用中失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆