CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    May 2010
    Posts
    14

    char input error help

    hi i tried a program wherein i declared an int variable. after running the program, whenever i input a character or string to the input variable, the program crashes. how could i prevent a user from inputting a character to the int variable? thanks

    EDIT: I'm using C.
    Last edited by rukix1x; July 3rd, 2010 at 11:10 AM.

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: char input error help

    One option is to read into a string, initialise a stringstream with that string, and then read from the stringstream into your int variable. You then check if the stringstream is in an error state after extracting from it.

    Alternatively, you continue to read directly into the int variable, but you check if the input stream is in an error state after extracting from it. If so, you clear the error state, discard characters (use the ignore member function) from the input stream, and continue reading.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  3. #3
    Join Date
    May 2010
    Posts
    14

    Re: char input error help

    im using c so how do i do it with c?

  4. #4
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: char input error help

    The basic thing is that you need to verify that the input was what you thought it was. There are two ways to do this.

    First, you could do essentially the same thing (read into a string, the process it) except using a fixed-size char array rather than the safer std::string since you're in C.

    Second, you could simply test the return value from scanf() to see if all expected conversions were successful. Note: if they weren't, you'll need to dispose of the troublesome characters in some way. A bunch of fgetc() calls will usually do the trick.

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured