How can i test data input and correct it if need be, such as if someone put a o instead of 0 or it has a raised digit like * instead of 8
Printable View
How can i test data input and correct it if need be, such as if someone put a o instead of 0 or it has a raised digit like * instead of 8
What did you think of? Why think of the problem like this anyway? Incorrect input is incorrect however you look at it, the fact that if somebody puts an * instead of an 8 means they accidentally depressed the shift key at the same time as keying the 8 is a moot point, it should just be filtered like any input error.
The key combos can differ quite widely anyhow depending on local settings, like USA keyboard versus UK etc etc,
Do you just mean you want to put clever error messages like "oops did you press the shift key also"??
i wouldn't bother, just output 'YA DUN TYPED WRONG PARD!' and make them do it again, and again, till they can get it RIGHT! :->
You can find a lot of help on validating input in the 'how do i..?' sections on the home pages'
You can mess around with strings and things.
I like this method but I don’t know if this is good or bad practise.
Code:#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main(){
string str_input;
float weight;
bool err = true;
while (err == true ){
err = false;
cout << "Enter weight in Kg's, zzz.zz : ";
getline (cin, str_input);
for (int i = 0; i < str_input.length(); i++)
if (!(isdigit(str_input[i]) || str_input[i] == '.'))
// Only 0-9 or '.' allowed
err = true;
if (str_input.length() > 6)
// Max 6 chars allowed
err = true;
int ndp = str_input.find('.');
if (ndp != string::npos)
if (str_input.find('.', ndp+1) != string::npos)
//Only 1 decimal point allowed
err = true;
else
if (ndp > 3)
// Max 3 leading chars allowed
err = true;
else
{
string dp = str_input.substr(str_input.find(".") +1);
if (dp.length() > 2)
// Max 2 dec places allowed
err = true;
}
if (err == true)
cout << "*Invalid format, must be 0-9 in format zzz.zz*" << endl;
}// end while loop
// Convert input string to float
istringstream ins;
ins.str(str_input);
ins >> weight;
cout << "Produce weighs " << weight << " Kg's" << endl;
system ("pause"); // temp to stop console closing
return 0;
}