Find the answer to your Linux question:
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 ...
  1. #1
    Linux Enthusiast meton_magis's Avatar
    Join Date
    Oct 2006
    Location
    arizona
    Posts
    665

    [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.

    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());
    };
    My problem is that due to the `while (!( atof(input.c_str())))` part, the function will not work if the input is 0.

    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.

    Thanks
    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

  2. #2
    Linux Enthusiast meton_magis's Avatar
    Join Date
    Oct 2006
    Location
    arizona
    Posts
    665
    Well I stumbled upon the answer I needed. I changed it to

    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');
      }
    };
    and the loop condition is true if cin gets any non numeric input, but will stop looping if somone enters 0.


    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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...