Limit Checking: Is the input a number?

Ok, please bear with me as I'm a "newbie" to both forums and C++.

I'm writing a program that converts between Celsius, Fahrenheit, and Kelvin for a C++ class project and I'm stuck on this one part:

When it asks for a numerical value (the value you want converted) if you enter something other than a number, a string, character, what have you, it gets stuck cycling through an endless loop. Essentially it breaks the program.

My instructor mentioned that there was some way to for the computer to check if it was a numerical input or not. He was unclear as to how this was done, vaguely suggesting the function ISNUMERIC. However, I don't know if you need a specific compiler directive to enable this function or even how to use it whatsoever.

I've done some looking around but haven't found any concise examples of how to implement this approach, or any other for that matter.

What I am trying to do is find some if statement that will check if the input is a numerical value and if it isn't then display some kind of "Invalid entry" message that will kick you back into the "Please enter the value you want converted." message.

Any suggestions or advice would be incredibly appreciated.

closed account (9y8C5Di1)
#include <string>
#include <sstream>

string sVar="";
float fVar=0;

getline(cin,sVar); //Let's input 5
stringstream(sVar)>>fVar;
cout<<fVar; //Prints 5
closed account (9y8C5Di1)

bool isCharNumber(char elem){

for(char a='0';a!='9'+1;a++){
if(elem==a)
return true;
}

return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int number ;

// as long as a number is not successfully read
while( std::cout << "type in an integer, then press <enter>: " && !( std::cin >> number ) )
{
    std::cout << "error: non-numeric input. " ; // tell the user about the error

    std::cin.clear() ; // clear the failed state of the input stream
    // http://www.cplusplus.com/reference/iostream/ios/clear/

    std::cin.ignore( 1000, '\n' ) ; // discard the non-numeric stuff in the input buffer
    // http://www.cplusplus.com/reference/iostream/istream/ignore/

} // and retry reading a number once more

// use number 
Topic archived. No new replies allowed.