Thread: avoid char input, help!

  1. #1
    Registered User
    Join Date
    Oct 2002
    Posts
    6

    avoid char input, help!

    supose

    i have to input a series of integer and count for odd and even number.

    However, would not allow to input character if mistake. In order to do that,
    the program should return to begin, but not to exit.

    I use
    cout<<"Enter an integer: ";
    cin>>integ;
    if (!cin)
    {cout<<"Enter again";
    cin>>integ;
    }

    but the program still exit.

    anyone can help?

  2. #2
    S Sang-drax's Avatar
    Join Date
    May 2002
    Location
    Göteborg, Sweden
    Posts
    2,072
    I haven't tested this function extensively, but I think it should work.

    Code:
    template<typename T> bool myget(T& t)
    {
        using std::cin;
        using std::ios;
        cin>>t;
        if (cin.eof())
            cin.clear();
        else if (cin.fail())
        {
            cin.clear(); 
            cin.ignore(10000,'\n');    
        }
        else if (cin.bad())
            cin.clear();
        else
        {
            cin.ignore(10000,'\n'); 
            return true;
        }
        return false;
    }
    Use it like this is main()

    Code:
    int main()
    {
      int integ;
      do
      {
         cout <<"Enter an integer: ";
      } while(!myget(integ));
      //...
    }
    Last edited by Sang-drax : Tomorrow at 02:21 AM. Reason: Time travelling

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sorting Linked Lists
    By DKING89 in forum C Programming
    Replies: 6
    Last Post: 04-09-2008, 07:36 AM
  2. The Interactive Animation - my first released C program
    By ulillillia in forum A Brief History of Cprogramming.com
    Replies: 48
    Last Post: 05-10-2007, 02:25 AM
  3. Obtaining source & destination IP,details of ICMP Header & each of field of it ???
    By cromologic in forum Networking/Device Communication
    Replies: 1
    Last Post: 04-29-2006, 02:49 PM
  4. How do you search & sort an array?
    By sketchit in forum C Programming
    Replies: 30
    Last Post: 11-03-2001, 05:26 PM