Results 1 to 2 of 2
Hey,
I'm trying to make a function to validate that integral values were entered on stdin.
here is what I have.
Code:
template <typename type>
void getSaneNumber(type &number)
{
number ...
- 07-07-2009 #1
[SOLVED] C++ input validation help
Hey,
I'm trying to make a function to validate that integral values were entered on stdin.
here is what I have.
My problem is that due to the `while (!( atof(input.c_str())))` part, the function will not work if the input is 0.Code:template <typename type> void getSaneNumber(type &number) { number = 0; number += 0; // make sure template is used for only numbers, or compatible std::string input; std::getline(std::cin, input, '\n'); while (!(atof(input.c_str()))) { std::cerr << "Invalid input, try again: " << std::flush; std::getline(std::cin, input, '\n'); } number = atof(input.c_str()); };
Anyone see a way of getting around this? If you have a suggestion for a better function to validate input as an integer (or float) then I'm open to suggestion, I just haven't seen anything better from googling.
ThanksNew to the internet, technical forums, or the hacker / open source community??
Read this to learn good posting habits http://www.catb.org/~esr/faqs/smart-questions.html
RHCE for RHEL version 5
RHCT for RHEL version 4
- 07-07-2009 #2
Well I stumbled upon the answer I needed. I changed it to
and the loop condition is true if cin gets any non numeric input, but will stop looping if somone enters 0.Code:template <typename type> void getSaneNumber(type &number) { number = 0; number += 0; while (!(std::cin >> number)) { std::cerr << "Invalid input, try again: " << std::flush; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); } };
NOTE:
All code posted by me in this thread is released for use under the GNU GPL V3, or by whatever licence is applicable under the terms of use of linuxforums.org.New to the internet, technical forums, or the hacker / open source community??
Read this to learn good posting habits http://www.catb.org/~esr/faqs/smart-questions.html
RHCE for RHEL version 5
RHCT for RHEL version 4


