Thread: Simple Gets() problem

  1. #16
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Take all user input as a string. If you need to convert to a number, attempt to convert to a number.




    Lather, rinse, repeat.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  2. #17
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Well it sounds like you (also) need to flush the input buffer, especially if you're looping the menu. You can use the ignore function from my previous post for that. For parts where you really need sentences, we covered that in great detail.

  3. #18
    The Richness... Richie T's Avatar
    Join Date
    Jan 2006
    Location
    Ireland
    Posts
    469
    here's how I use fgets:

    Code:
    #include <stdio.h>
    #include <string.h>
    
    char *strget (char *str, int size, FILE *ip)
    {
    	char *pointer;
    	int clear;
    	char *ret;
    
    	ret = fgets (str, size, ip);
    
    	if ((pointer = strchr(str, '\n')) != NULL)	/*if newline is present*/
    		*pointer = '\0';			/*change it to \0*/
    
    	/*otherwise there is at least one character in the buffer, so flush it*/
    	else while ((clear = getchar ()) != '\n' && (clear != EOF));
    
    	return ret; /*return fgets's return value just in case*/
    }
    The above code was written for C, hence the headers and stuff.
    What it does is uses fgets to read in a string, removes the
    newline if necessary and flushes the buffer if necessary -
    everyone should have a function like this IMO. You can use it in
    main just like fgets as normal, but it cleans up after itself. Then
    do as Dave_Sinkula and citizen have said.
    Last edited by Richie T; 05-25-2006 at 03:40 AM.
    No No's:
    fflush (stdin); gets (); void main ();


    Goodies:
    Example of fgets (); The FAQ, C/C++ Reference


    My Gear:
    OS - Windows XP
    IDE - MS Visual C++ 2008 Express Edition


    ASCII stupid question, get a stupid ANSI

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A simple file I/O problem
    By eecoder in forum C Programming
    Replies: 10
    Last Post: 10-16-2010, 11:00 PM
  2. Problem in simple code.
    By richdb in forum C Programming
    Replies: 6
    Last Post: 03-20-2006, 02:45 AM
  3. Problem in very simple code
    By richdb in forum C Programming
    Replies: 22
    Last Post: 01-14-2006, 09:10 PM
  4. Simple Initialization Problem
    By PsyK in forum C++ Programming
    Replies: 7
    Last Post: 04-30-2004, 07:37 PM
  5. Simple OO Problem
    By bstempi in forum C++ Programming
    Replies: 1
    Last Post: 04-30-2004, 05:33 PM