Hello.
I'm writing a program and I need it to accept input from the user in main, and then call a function that will validate that input as a legal float data type.
I've tried to accept user input as a string, then iterate through the string to make sure all characters are acceptable float characters.
But I'm realizing I don't know how to do it very well, and need help figuring out a good method for input validation.
Here's my code. It isn't finished, and doesn't work well. But I feel pretty stuck with my knowledge.
#include <iostream>
#include <string>
#include <cmath>
#include <cstdlib>
usingnamespace std;
float valid_float(string str){
int dot = 0;
float val;
for(int j = 0; j < str.length(); j++){ // This is a lame attempt to make sure there is only a single '.' in the answer, and no more.
if(str[j] == 46){
dot += 1;
}
if(dot > 1){
return 0000000000000001;
}
}
for(int i = 0; i < str.length(); i++){
if(!(str[i] >= 48 && str[i] <= 57)){
// Cast string as a float
}
}
}
int main(){
float x;
string input;
do{
cout << "\nPlease enter a valid float: " << endl;
cin >> input;
x = valid_float(input);
}while(x == 0000000000000001); // This is supposed to catch errors when a user enters more than one '.'
return 0;
}
Don't use numeric codes for characters. Just say '.' and '0', etc.
Do you think those leading zeroes are doing something? It's still just 1.
If you want a special value to return if you weren't able to convert the string you could return NaN (numeric_limits<double>::quiet_NaN()). Test it with isnan().
Anyway, if you haven't already tried to do this exercise with an int, then I'd start there first.
// if valid float, place the result of the conversion in value and return true
// return false if the entire string could not be interpreted as float
bool valid_float( std::string str, float& value )
{
// remove trailing white space, if any
while( !str.empty() && std::isspace( str.back() ) ) str.pop_back() ;
// https://en.cppreference.com/w/cpp/string/basic_string/stof
std::size_t pos = 0 ;
try { value = std::stof( str, &pos ) ; } // try to interpret the string as float
catch( const std::exception& ) { returnfalse ; } // conversion failed: not a valid float
return pos == str.size() ; // valid float if all characters in the string have been consumed
}
#include <iostream>
#include <sstream>
#include <string>
usingnamespace std;
bool isValidFloat( string s, float &f )
{
char junk;
stringstream ss( s );
return ( ss >> f && !(ss >> junk) );
}
int main()
{
float f;
string tests[] = { "1", "2.0", "3.5e4", "3.5e400", " -3.145 ", "2.5 3.6", "abc" };
for ( string s : tests )
{
if ( isValidFloat( s, f ) ) cout << "\"" << s << "\" is the valid float " << f << '\n';
else cout << "\"" << s << "\" is not a valid float\n";
}
}
"1" is the valid float 1
"2.0" is the valid float 2
"3.5e4" is the valid float 35000
"3.5e400" is not a valid float
" -3.145 " is the valid float -3.145
"2.5 3.6" is not a valid float
"abc" is not a valid float