parsing - Requiring valid float input from stdin to have precision of 2 in C++ -
let reading float std::cin or file, , want enforce condition has 2 trailing decimal places:
e.g.
4.01 (valid)
4.001 (invalid - has 3 trailing decimal places)
a,47 (invalid, has 2 non [0-9] characters in 'a' , ',')
#556.53 (invalid, has '#')
(just context, in example, parsing text file several entries separated spaces, validating each input, , storing them in struct further processing.)
how it?
i found other sources in stackoverflow.
c++ how check input float variable valid input
here implementation. read string , accept if of characters not digits (in perl, suppose regex non-match [0-9]).
apparently, find_first_not_of method in string us:
std::string a; if(!(std::cin>>a)){ std::cout << "invalid float entry " << std::endl; } if(a.find_first_not_of("1234567890.-")!=std::string::npos){ std::cout << "invalid string float" << std::endl;} next, verify string has 2 decimal places searching location of decimal point.
if(a.size()-a.find(".")!=3){ std::cout << "valid float must have 2 decimal places \n"; }else{ std::cout << "accept - valid float , has 2 decimal places \n"; } finally, convert float using stof.
float u = stof(a);
Comments
Post a Comment