cin.fail()〜当我输入例如“45nj”时,为什么cin不会失败?或“-4.2356rg”?? [英] cin.fail() ~ Why cin does not fail when I type for example "45nj" or "-4.2356rg"??

查看:93
本文介绍了cin.fail()〜当我输入例如“45nj”时,为什么cin不会失败?或“-4.2356rg”??的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,有没有可能帮我解决这个问题???

Hi there, is there any possibility to help me with this problem???

当我给出像"hj435"这样的值时或"e"或"e"。到cin>> number_Value,cin.fail()正常工作。但是当输入"45mbwwe"时或"-3.5652qbpo"或"-3.5652qbpo"。 cin.fail()无法正常工作。 cin.fail()仅查看数字部分
并忽略字符,就像从未输入一样。 

When I give a value like "hj435" or "e" to cin >> number_Value, cin.fail() works normally. But when typing "45mbwwe" or "-3.5652qbpo" cin.fail() does not work as I would like. cin.fail() sees the number part only and ignores the characters as if never typed. 

这是一个代码示例: 

Here is an example of codes: 

或 

while(!(cin>> num))

{

cerr<< "你没有输入数字。请输入一个数字:" ;;

cin.clear();

cin.ignore(numeric_limits< std :: streamsize> :: max(),'\ n');


}

while(!(cin >> num))
{
cerr << "You did not input a number. Please, input a number: ";
cin.clear();
cin.ignore(numeric_limits<std::streamsize>::max(), '\n');
}

谢谢!

推荐答案

使用123abc这样的值,提取实际上成功了因为从流中提取了123

。在某些情况下,在
流中仍有数据的事实可能是有效的。考虑:



int n;

string str;

cin>> n>>海峡; //我们不希望这在123abc上失败



如果你想在成功的数字提取后检查,看看是否有
是流中剩下的数据,考虑使用cin.peek()来查看字符串中的下一个

字符是否为'\ n',它应该用于诸如
的条目


123< enter>



但不会用于诸如b $ b的条目
123x< enter>



- Wayne


With values such as 123abc the extraction actually succeeds as the 123
is extracted from the stream. The fact that there is still data in the
stream may be valid in some cases. Consider:

int n;
string str;
cin >> n >> str; // we don't want this to fail on 123abc

If you want to check after a successful numeric extraction to see if there
is data left in the stream, consider using cin.peek() to see if the next
character in the string is a '\n' which it should be for entries such as

123<enter>

but won't be for entries such as

123x<enter>

- Wayne


这篇关于cin.fail()〜当我输入例如“45nj”时,为什么cin不会失败?或“-4.2356rg”??的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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