Error Trapping

Discussion in 'C++' started by arholub, Jul 27, 2012.

  1. arholub

    arholub New Member

    Joined:
    Jul 27, 2012
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Retired
    Location:
    Southern California
    Home Page:
    http://www.arholub.com
    Windows 7, Visual Studio 2010, C++

    int main()
    {
    float x,y;
    do{
    cout<<endl;
    cout<<"Please enter a number greater than 3 and less than 9 ";cin>>x;
    if(x<3 || x>9)
    cout<<"ERROR"<<endl;
    }while(x<3 || x>9);

    more code for y....

    ***********************
    Above code works fine for float x ; Want to trap error if x is ALPHA.
    How???? (I haven't coded in a while)
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    You would have to read the input into a string variable, then check if it's a valid number with a function like atoi(), and if not, throw a suitable error.
    Code:
    char buf[32];
    fgets(buf,30,stdin); // order of params might be wrong
    int num=atoi(buf);
    if (num<3 || num>9) printf("Wrong\n");
    
     
  3. arholub

    arholub New Member

    Joined:
    Jul 27, 2012
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Retired
    Location:
    Southern California
    Home Page:
    http://www.arholub.com
    Thank you...good start...

    need: float num=ATOF(buf);.....

    Now working....

    Really like this forum...Thanks again...
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice