>#include<conio.h> //provides clrcsr()
Not necessarily. conio is a nonstandard library, and it's contents will vary with each implementation. Why do you need to clear the screen anyway? That seems pretty antisocial to me in most cases.
>cin >> temp;
>if(isdigit(temp))
And this works for you by some miracle? Let's take it bit by bit (yes it's a pun, yes it was intended). cin's >> operator converts values based on the type of the variable you pass to it, in this case int. So cin will fail if anything but a digit is entered and the contents of temp will be indeterminate. Now, if this indeterminate value happens to not be within the range of unsigned char, passing it to isdigit results in undefined behavior.
So, let's come up with a solution and actually test it this time:
Code:
#include <iostream>
#include <cstdlib>
void bad_input()
{
std::cerr<<"Invalid input entered, bailing..."<<std::endl;
std::exit ( EXIT_FAILURE );
}
int main()
{
int vals[10];
for ( int i = 0; i < 10; i++ ) {
if ( !( std::cin>> vals[i] ) )
bad_input();
}
}
This works, but it relies on a failure state and isn't very flexible if you want to perform different operations based on what the invalid input was. Fortunately, we can fix the second part easily by using a more robust function:
Code:
#include <iostream>
#include <cstdlib>
#include <string>
void stop_input ( int vals[], int n )
{
std::string stop;
std::cin.clear(); // Make cin usable again
// Read the extraneous data as a string
// because we don't know how to convert it
if ( std::getline ( std::cin, stop ) ) {
// Valid stop condition
if ( stop == "stop" ) {
std::cout<<"You entered: ";
for ( int i = 0; i < n; i++ )
std::cout<< vals[i] <<' ';
std::cout<<std::endl;
std::exit ( EXIT_SUCCESS );
}
else { // Invalid condition
std::cerr<<"Error: Invalid input"<<std::endl;
std::exit ( EXIT_FAILURE );
}
}
}
int main()
{
int vals[10];
for ( int i = 0; i < 10; i++ ) {
if ( !( std::cin>> vals[i] ) )
stop_input ( vals, i );
}
}
The first part, where you rely on an error condition to direct potentially valid input, is considered by some to be bad style, but cleaning the stream and validating the data is relatively simple, so make your own decision about it.