Trapping input

This is a discussion on Trapping input within the C++ Programming forums, part of the General Programming Boards category; Im kinda newbish right now, but is there a way to stop people from entering the wrong type of input? ...

  1. #1
    Registered User dragon_man's Avatar
    Join Date
    May 2003
    Posts
    6

    Question Trapping input

    Im kinda newbish right now, but is there a way to stop people from entering the wrong type of input?

    Code:
         main()
          {
            int a;
            cout << "Enter a number";
            cin >> a;
          }
    If they enter a char for the input the program locks-up. Is there a way to catch those?
    Last edited by dragon_man; 05-13-2003 at 08:52 PM.

  2. #2
    Registered User slaveofthenet's Avatar
    Join Date
    Apr 2003
    Posts
    80
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    	int a;
    	bool flag = false;
    	for (;;)
    	{
    		cout << "Enter a number: ";
    		cin >> a;
    		if (cin.fail())
    		{
    			cin.clear();
    			cin.ignore(100, '\n');
    			cout << "Invalid Input!\n";
    		}
    		else
    			break;
    	}
    	cout << "Your number is: " << a << endl;
    	return 0;
    }

  3. #3
    Registered User dragon_man's Avatar
    Join Date
    May 2003
    Posts
    6
    Thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Input statement problem
    By une in forum C Programming
    Replies: 3
    Last Post: 05-29-2007, 11:16 PM
  2. For loop problems, input please.
    By xIcyx in forum C Programming
    Replies: 2
    Last Post: 04-22-2007, 03:54 AM
  3. I would love some input on my BST tree.
    By StevenGarcia in forum C++ Programming
    Replies: 4
    Last Post: 01-15-2007, 12:22 AM
  4. Simple Console Input for Beginners
    By jlou in forum C++ Programming
    Replies: 0
    Last Post: 06-21-2005, 01:50 PM
  5. Stupid Question
    By digdug4life in forum C++ Programming
    Replies: 22
    Last Post: 05-17-2005, 11:43 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21