将输入限制为整数 [英] restrict input to integer

查看:83
本文介绍了将输入限制为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int a[5];
    for(int i=0;i<5;i++)
    {
            cin>>a[i];
    }


问题在于,当我们在数组中输入错误的值时,它将获得垃圾值,而下一次迭代cin不会从键盘中获取新值.
我想避免键盘输入错误.这怎么可能?

例如
1
2
f
现在,"cin"将不再需要键盘输入.


The problem is that when we give wrong value in array it takes a garbage value and next iteration cin doesn''t take new value from keyboard.
I want to avoid wrong input from keyboard. how is this possible?

e.g.
1
2
f
now "cin" will not take further input from keyboard.

推荐答案

好吧,接受不同的输入.换句话说,请验证传入的数据以确保它是您想要/期望的.我会给你一些提示:

0)您没有*必须*直接将数据接受到数组中

1)该数组没有*必须是整数数组.

继续,然后编写代码.
Well, accept input differently. In other words, validate the incoming data to make sure it''s what you want/expect. I''ll give you some hints:

0) You don''t *have* to accept the data directly into the array

1) The array doesn''t *have* to be an array of integers.

Go forth, and code.


这可能是因为有人在输入程序不期望的数据.这里发生的是,当流看到不可转换为整数的字符输入时,会将流设置为失败状态.如果要使它脱离失败状态,则必须:

-检测流何时进入失败状态
-设置好后,将流设置为良好状态
-清除将流置于该状态的输入

每个人都是关于循环中另一行代码的.看看您的编译器对std::istream的参考,它应该为您指明正确的方向.

干杯,



PS:Kreft和Langer撰写的标准C ++ IO流和语言环境:高级程序员指南和参考"是一本使用iostream的宝贵著作.即使使用该语言已有近20年的时间,也值得一买,也是我最常用的参考文献之一.
It''s possible because someone''s entering data the program isn''t expecting. What''s happening here is that when the stream sees the input of a character that isn''t convertible to an integer it sets the stream into a fail state. If you want to get it out of the fail state you have to:

- Detect when the stream enters the fail state
- When it does, set the stream to a good state
- Purge the input that put the stream in that state

Each one''s about another line of code in your loop. Have a look at your compiler''s reference for std::istream and that should point you in the right direction.

Cheers,

Ash

PS: "Standard C++ IO Streams and Locales: Advanced Programmers Guide and Reference" by Kreft and Langer is an invaluable book for using iostreams. It''s well worth a buy and one of my most used references, even after using the language for nearly 20 years.


hi,

我还建议您与上面发布的评论相同.首先,从键盘取值到Integer中,然后检查验证.如果输入介于0到9之间,则将该值分配给您的整数数组.该代码可能如下所示:

int a [5],x;

for(int i = 0; i< 5; i ++)
{

cout<< 请输入一个整数"
cin> x
如果(!isdigit(x))
cout<< 这不是有效的输入\ n";
其他
a [i] = x;

}


I also suggests you the same as above posted comments. Firstly fetch values from keyboard into an Integer then check for the validation. If the input is in between 0 to 9, then assign that value into your integer array. The code might look somewhat as below:

int a[5], x;

for(int i=0; i < 5; i++)
{

cout<< " Pls enter an integer"
cin>> x
if ( !isdigit ( x ) )
cout<< "That is not a valid input \n";
Else
a[i] = x;

}


这篇关于将输入限制为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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