Results 1 to 4 of 4

Thread: C++ " Try {" Question.

  1. #1
    Join Date
    Dec 2009
    Beans
    40

    C++ " Try {" Question.

    Hokay so this is a seemingly basic question. Im attempting to limit a persons input so that if they put in a string instead of number, and error occurs, the program won't end.

    Was using python before and was wondering how to convert it into a C++ code.

    This is what i have so far.

    PHP Code:
        while (x==0) {
              try {
                  
    //Enter some cin code here
                  
    x++ //Assuming that this code wouldnt work UNLESS the cin didn't result in error.
                  
    }
              
    except ValueError // The python code that would go here. (From my limited experience.) 
    Also have 2 more questions, 1 of which deals with user input again.

    1:What do i do if I want to limit user input to a specific # of characters? (Could google this one BUT I'm already making a thread so yea)

    2:How would I be able to extract 2 numbers from one input.

    cin >>xy // entered in the form x,y

    and i want to extract the x and the y seperately.
    Last edited by YourMomsASmurph; January 10th, 2010 at 01:43 AM.

  2. #2
    Join Date
    Dec 2009
    Location
    las vegas, nv, usa
    Beans
    72
    Distro
    Ubuntu 9.10 Karmic Koala

    Re: C++ " Try {" Question.

    try {...} catch(...) {...}
    check this : http://www.java2s.com/Tutorial/Cpp/0..._try-catch.htm

    cin >> x >> y; // to read x and y

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

    Re: C++ " Try {" Question.

    I don't think you need the try-catch(es).

    Something like this would suffice:
    Code:
    #include <iostream>
    
    int main()
    {
      using namespace std;
    
      int  x, y;
      bool inputGood = false;
    
      do
      {
         cout << "Enter two numbers, separated by a white-space: ";
         cin >> x >> y;
    
         inputGood = cin.good();
    
         if (!inputGood)
         {
           cerr << "Damn it... I said to enter two numbers!\n" << endl;
           cin.clear();
           cin.ignore(1024, '\n');
         }
      } while (!inputGood);
    
      // do something with the two numbers
      ...
    }

  4. #4
    Join Date
    Apr 2009
    Location
    Germany
    Beans
    2,134
    Distro
    Ubuntu Development Release

    Re: C++ " Try {" Question.

    but you can use exceptions by setting the exception flag for the stream:
    http://www.cplusplus.com/reference/i...os/exceptions/

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
  •