Entering non-numeric input into variable of type double

I want a program that lets the user keep entering numbers into a variable of type double.

The program should terminate input on non-numeric input. (This is where I'm getting stuck; what should be the condition of the while loop?)
hi Thomas

it may be a little complex, but a combination of isalpha and atof will do the trick.

you need to store the input into a string, and then check the string with isalpha. excerpt from cplusplus on isalpha below. you could read more in http://www.cplusplus.com/reference/clibrary/cctype/isalpha/
Checks if parameter c is either an uppercase or a lowercase alphabetic letter.

if the string passes the check, then we can safely assume that it is all digits. also, the dot in the double will not be considered as an alphabet. then you use atof, and convert it into double. you could read more in http://www.cplusplus.com/reference/clibrary/cstdlib/atof/

hope this helps
1
2
3
4
5
6
7
8
9
10
11
double number ;
while( std::cout << "number? " && std::cin >> number )
{
    // do whatever with number
}

// clear the error state and discard invalid input
std::cin.clear() ;
std::cin.ignore( 1024, '\n' ) ;

// use std::cin again 
JLBorges wrote:
std::cin.ignore( 1024, '\n' ) ;


What does this line do?

And by the way, I can put the cout within the loop, rather than as a condition.
Last edited on
> What does this line do?

It extracts and discards the invalid characters in the input buffer.
http://www.cplusplus.com/reference/iostream/istream/ignore/


> I can put the cout within the loop

You can.
1
2
3
4
5
6
std::cout << "number? " ;
while( std::cin >> number )
{
    // do whatever with number
    std::cout << "number? " ;
}


Topic archived. No new replies allowed.