Click here to Skip to main content
15,921,542 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
Right basically I want to know how to declare the program to not screw up when someone enters a character

I thought it might be something like

while( height != 'float')loop etc

but that dose not work and it does screw up. Please help!
Posted

You could define the rules that define a number and simply create code for that
You would need code to rules like:
1. can start with an optional minus ('-')
2. 1 or more digits ('0'..'9')
3. optional a single dot ('.') and again no 2.

A second option is to consider using a regex expression (this example only accepts digits 0..9).
C#
string Temp = "Hax00r L33t";
string Output = Regex.Replace(Temp, "[^0-9]", "");


Good luck!
 
Share this answer
 
Hi,

Keyboard input validation is always a challenge. This function handles some usual cases:
C++
#include <sstream>
template <class Num>
bool Validate(const std::string& input, Num& num)
{
    Num tmp;
    std::istringstream iss(input);
    iss >> std::skipws >> tmp >> std::skipws;
    return iss.eof() && !iss.fail() ? num = tmp, true : false;
}

Check with:
C++
#include <iostream>
int main()
{
    std::string input;
    for (;;)
    {
        std::getline(std::cin, input); // get all input
        int i = 0;
        bool bint = Validate(input, i);
        float f = 0;
        bool bfloat = Validate(input, f);
    }
    return 0;
}


"123", " 123 " "-123" are validated as int and float.
"12 3", " 12 3 " "- 123" are invalidated as int and float.
"123.", " .123 " "-12.3" " -.123e4 " are invalidated as int and validated as float.

cheers,
AR
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900