0

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.

2
Contributors
1
Reply
2
Views
9 Years
Discussion Span
Last Post by vijayan121
0

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" ;
  }
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.