Thread: why doesn't this work??

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    54

    Question why doesn't this work??

    //function that gets a message from the user and displays an error message if
    //the message is greater than 27 characters
    void getMessage(char data[CHARS])
    {
    printf("Please enter the message(MAX %d Chars) - ",CHARS);
    gets(data); //get user input

    while(strlen(data)>CHARS) //loop if string length is greater than 27
    {
    printf("Maximum is %d characters, please re-enter - ",CHARS);
    gets(data); //get user input
    };
    }
    //end getMessage function

    if the number of charaters is below 27 everything works fine but as soon as i type more than 27 chars i need to re-enter another string, so i enter another string, when i try to exit the program i get an access violation error, does anyone have any ideas

    thanx in advance

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > while(strlen(data)>CHARS) //loop if string length is greater than 27
    Because at the moment this becomes true, the damage has already been done, and there is no way out.

    http://www.eskimo.com/~scs/C-faq/q12.23.html

    There is NO (repeat NO) way to use gets, and prevent it from trampling over somewhere where it shouldn't.

    Always (repeat ALWAYS) use fgets for reading input from a file (or the user via stdin)
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. strcmp returning 1...
    By Axel in forum C Programming
    Replies: 12
    Last Post: 09-08-2006, 07:48 PM
  2. getline() don't want to work anymore...
    By mikahell in forum C++ Programming
    Replies: 7
    Last Post: 07-31-2006, 10:50 AM
  3. Why don't the tutorials on this site work on my computer?
    By jsrig88 in forum C++ Programming
    Replies: 3
    Last Post: 05-15-2006, 10:39 PM
  4. fopen();
    By GanglyLamb in forum C Programming
    Replies: 8
    Last Post: 11-03-2002, 12:39 PM
  5. DLL __cdecl doesnt seem to work?
    By Xei in forum C++ Programming
    Replies: 6
    Last Post: 08-21-2002, 04:36 PM