CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Catching Input error

  1. #1
    Join Date
    Jun 2008
    Posts
    1

    Catching Input error

    Hi, I'm new to the forum, and I'm sorta new to programming, and I have a pretty simple question. (I hope)

    I need to know how to handle an error when someone puts something other than a number into a double(like a letter)

    Here's a small example:

    Code:
    double a;
    cout << "Insert a number: ";
    cin >> a;
    This is where if a letter is inserted the program starts to flicker and crashes and stuff, if a letter is put in.

    So, please someone show me how to catch the input error and maybe re-ask them for the value?

    Thanks again!

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,768

    Re: Catching Input error

    You could do something along these lines:
    Code:
    double a;
    for (;;)
    {
        cout << "Insert a number: ";
        if (cin >> a)
        {
            break;
        }
        else
        {
            cout << "Sorry, invalid input.\n";
            cin.clear();
            cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
    }
    The cin.clear() clears the error state of the stream so you can get input again. The cin.ignore() removes the incorrect input from the stream so that it will not be read again (unless the user happens to enter the same thing).

    A simplified version, which might or might not amount to code obfuscation, would be:
    Code:
    double a;
    while ((cout << "Insert a number: "), !(cin >> a))
    {
        cout << "Sorry, invalid input.\n";
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    You could also simplify by writing a function and using it with a do while loop.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

Posting Permissions

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


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)