Hey guys.

I need some help on input validation in an array. The program can only input numbers but not characters.

This is the code for the input. ( I know im a newbie lol )

const arraysize = 10;
float num[arraysize];
for ( int i = 0; i < 10; i++ ){
	cout << endl << "Enter number  " << i + 1 << "  :\t";
	cin >> num[i];		//Array input
}

I need to produce an error message and break out from the program when the input is not a number (character etc). The program is in a function.

the input may not be a number due to several reasons:
a. it may be empty
b. it may have invalid characters
c. it may be too long
d. it may have an invalid format eg. 45.73.2 or +-42

the simplest way to validate is perhaps
a. read the input as a string.
b. try to convert the string to a number.
c. if the entire input is consumed in step b., the input is ok.

#include <iostream>
#include <string>
#include <sstream>
double get_it()
{
  std::string input ;
  while( true )
  {
    std::cout << "please enter a number followed by a newline: " ;
    std::getline( std::cin, input ) ;
    std::istringstream stm( input ) ;
    double value ;
    if( ( stm >> value )  && stm.eof() )  return value ;
    else std::cout << "*** error in input \'" << input << "\'\n" ;
  }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.