data validation and clearing the stream

I am trying to learn the best way to validate data of type float. There are plenty of topics to be found on data validation around but most of the answers do not go indepth enough in explaining how to implement their recommended methods for them to help me. for example: the answer "Get the input as a string, then check if it's a number or not." does not explain the process involved and thus does not help a beginner such as myself.

Right now the only validation code that i have been able to implement is to allow only positive numbers to be input :

1
2
3
4
5
6
7
   while (loanAmount < 0) 
         {
          cout << "INVALID DATA" << endl;               
          cout << "loan amount must not be negative number" << endl;
          cout << "try again:" << endl;
          input (loanAmount, yearlyRate , monthlyPayment, monthlyRate, desiredYears);
         }


If a letter or symbol is input into my program it goes bonkers. What is the best way to avoid this? How can I do that?


Also, I read it is important to clear the stream or something like that after invalid data has been entered. Should I worry about this? what does this mean?

Thanks!
Last edited on
the atof() function takes a char* and attempts to converts it to a float, if it fails it returns 0.
how would I use this?
Some poster in this forum point me to C++ classes called ostringstream and istringstream that can do what we want previously like sprintf does.

istringstream >> varFloat; //extract the string version of say "3.14" into a float variable

ostringstream << varFloat; //input the float variable 5.15 into as string "5.15"

I forget that poster name but his posts provide me another C++ class we can use to do such "casting" between string and primitive types.

1
2
3
4
5
6
7
8
9
  float varFloat = .0f;
  istringstream istr("3.14");
  istr >> varFloat;
  cout << varFloat << "\n";

  varFloat = 5.15f;
  ostringstream ostr;
  ostr << varFloat;
  cout << ostr.str() << "\n";
Topic archived. No new replies allowed.