cin未能在while循环中停止 [英] cin fails to stop while loop

查看:66
本文介绍了cin未能在while循环中停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道你们是否可以向我解释,如果我输入'r'作为'value'的值,为什么这个循环不会循环.

 双精度值std :: cout<<请输入真实数字:";std :: cin>>价值;而(!isdigit(value)){std :: cout<<抱歉,但只有数字有效.\ n请输入真实数字:";std :: cin>>价值;} 

非常感谢您.

解决方案

您不应在此处使用 isdigit(),因为这是为了测试是否是单个 char 类型是一个 ASCII 数字.

如果您希望用户输入一个实数(而不是一个字符串),则应使用 cin.fail()作为循环测试条件.如果 cin 在期望 double 时读取字符串,则 cin.fail()将返回 true .

另一个(更清洁的)选项是按照 @bennofs 所指出的那样测试 cin 的状态:

  while(!(std :: cin>>值)){//输入了错误的值} 

I was wondering if you guys could explain to me why this loop doesn't loop if I enter 'r' in for the value of 'value'.

double value

std::cout << "Please enter a real number: ";
std::cin  >> value;

while (!isdigit(value))
{
    std::cout << "Sorry, but only numbers are valid.\nPlease enter a real number: ";
    std::cin  >> value;
}

Thank you very much.

解决方案

You shouldn't be using isdigit() here because that's for testing whether a single char type is an ASCII digit.

If you're expecting the user to enter a real number (and not a string), then you should use cin.fail() as your loop test condition. If cin reads a string when it's expecting a double then cin.fail() will return true.

Another (cleaner) option is to just test the state of cin as @bennofs pointed out:

while (!(std::cin >> value))
{
    // bad value was entered
}

这篇关于cin未能在while循环中停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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