Click here to Skip to main content
15,891,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
int a[5];
    for(int i=0;i<5;i++)
    {
            cin>>a[i];
    }

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.
Posted

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.
 
Share this answer
 
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.
 
Share this answer
 
hi,

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;

}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900