dcsimg
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: String Input Crashes Program

  1. #1
    Join Date
    Oct 2009
    Posts
    8

    String Input Crashes Program

    I am accepting integer input only for my program, my program does not know what to do when non integer characters are entered and thus crashes. I want to be able to disregard any non-integer input whether it be char's/symbols etc. What line of code would I use to do so?

    This is what i currently have for an example..

    Code:
            while(counter2 < 1) {
    
            printf("What is your vehicle class?\n\t[1 = Light | 2 = Heavy Single | 3 Heavy Multiple]\n");
                    scanf("&#37;d", &vclass);
            if(vclass == 1 || vclass == 2 || vclass == 3){
                    counter2++;
                    break;
                                                         }
            else{
                    printf("ERROR; Please enter a valid input.\n");
                }
            }
    In my IF statement, i want to disregard any non integer input, so i'm wondering what i'll have to implement in order to do so, thanks.
    Last edited by 1991dan; October 6th, 2009 at 10:27 AM.

  2. #2
    Join Date
    Jun 2008
    Posts
    2,477

    Re: String Input Crashes Program

    This is a C# forum, and that code is not C#, so I am not sure that you posted in the correct place. I see that this is now the second C code example that you have posted in this forum, not sure what is going on... so here is the .NET answer:

    .NET has many built in helper functions. The best way would be to simply disallow the user from entering non-integral data, be it with a MaskedTextBox, a regular expression, or by using the String class' built in methods (like Contains()). Another way would be to use the TryParse method:

    Code:
    string s = textbox1.Text;
    int i = 0;
    if ( int.TryParse( s, i ) )
    {
        // work with i, the data is valid
    }
    else
    {
        MessageBox.Show( "Please enter valid integral data." );
    }
    Last edited by BigEd781; October 6th, 2009 at 05:54 PM.

Posting Permissions

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


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)