Results 1 to 3 of 3

Thread: [C++] Avoiding Characters Stored in an Integer

  1. #1
    Join Date
    Nov 2008
    Beans
    4

    [C++] Avoiding Characters Stored in an Integer

    First off, I did Google this with no good results...

    I have a console program and it takes integers as options. However, when I put in a letter as an answer the program messes up. How do I prevent character(s) from being stored in an integer?

    int option;
    cin >> option;

  2. #2
    Join Date
    Jun 2007
    Location
    Maryland, US
    Beans
    6,288
    Distro
    Kubuntu

    Re: [C++] Avoiding Characters Stored in an Integer

    cin will not store characters in an integer.

    If you query for an integer using cin, and the user enters one or more characters (followed by 'enter'), then cin will fail. You can verify this by calling cin.fail().

    To clear cin's error state, you need to call cin.clear(), followed by a call to cin.ignore() remove unwanted characters from the data stream.

    For example:
    PHP Code:
    ...
    int value 0;

    while (
    true)
    {
      
    std::cout << "Enter a number: ";
      
    std::cin  >> value;

      if (
    std::cin.fail())
      {
        
    std::cin.clear();
        
    std::cin.ignore(1024'\n');  // ignore at most 1024 characters until '\n' found
      
    }
      else
        break;  
    // all good; we got a value
    }
    ... 
    Last edited by dwhitney67; November 15th, 2008 at 11:17 PM.

  3. #3
    WW is offline Iced Blended Vanilla Crème Ubuntu
    Join Date
    Oct 2004
    Beans
    1,532

    Re: [C++] Avoiding Characters Stored in an Integer

    Nevermind... I should test more before posting code.
    Last edited by WW; November 16th, 2008 at 04:55 AM. Reason: Removed code that didn't quite work.

Bookmarks

Posting Permissions

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