c++:仅为cin整数

c++: cin integer only

本文关键字:整数 cin 仅为 c++      更新时间:2023-10-16

我试图使用try-catch块验证输入,但遇到了一个小问题。

如果在第一个循环中,用户要输入数字,然后是字母(123abc(,程序会直接跳到第二个循环,不会给出错误,但如果相反(abc123(,则错误消息会正常工作。

此外,如果在输入int时,他们输入了一个双值(45.1(,那么程序将45作为int(x(,将0.1作为double(y(。我需要它抛出错误,或者如果它只是将数字四舍五入到最近的整数值,我会很高兴

代码:

int x;
double y, z;
while (1)
{
    try 
    {
        std::cout << "Enter an int (x): ";
        if (std::cin >> x && x > 0) { break; }
        else if (!std::cin) { throw x; }
        else { throw x; }
    }
    catch (int)
    {
        std::cout << "Error: Not a valid integer.nn";
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
    }
}
while (1)
{
    try
    {
        std::cout << "Enter a double (y): ";
        if (std::cin >> y && y > 0) { break; }  
        else if (!std::cin) { throw y; }
        else { throw y; }
    }
    catch (double)
    {
        std::cout << "Error: Not a valid double.nn";
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
    }
}
z = x + y;
std::cout << "nn" << x << " + " << y << " = " << z;

我会写一个函数,它接受一行输入,从int中提取一个int,并检查是否还有其他垃圾。我使用std::ws操纵器来消除尾部空白,这不应该是错误

bool parse_int(int& i)
{
    std::string line;
    std::getline(std::cin, line);
    std::istringstream iss(line);
    return (iss >> i && (iss >> std::ws).peek() == EOF);
}

然后将其用作:

int i;
if ( parse_int(i) ) /* ok */

或者,如果您不关心冗余数据,您可以在使用istream::ignore获得int后忽略它。

此外,抛出算术类型也很奇怪。std::logic_error异常类的某些子类会更合适。

int main()
{
 std::stringstream ss;
 int x;
 ss << "123abc";
 ss >> x;
 std::cout << x << std::endl; // 123 
 // And   
 ss << "abc123";
 ss >> x;
 std::cout << x << std::endl; // 0 
 return 0;
}

流逐个处理每个字符,并根据请求的类型为无效字符停止。