Thread: fgets?

  1. #1
    venus
    Guest

    fgets?

    hi there.

    could somebody tell me how to use fgets instead of scanf in the example below? thank you.

    Code:
    void read_date(int *yyyy, int *mm, int *dd) {
    	int i;
    
    	while(1) {
    
    		printf("Enter date (YYYY MM DD): ");
    		i = scanf("%d %d %d", yyyy, mm, dd);
    
    
    		if(i == 3) {
    			if((*yyyy < 1) || (*yyyy > 9999)) {
    				printf("YYYY must be between 0 and 9999\n");
    				continue;
    			}
    			if((*dd < 1) || (*dd > days_month[*mm-1])) {
    				printf("DD must be between 1 and %d for the month of %s\n", days_month[*mm-1], months[*mm-1]);
    				continue;
    			}
    			if((*mm < 1) || (*mm > 12)) {
    				printf("MM must be between 1 and 12\n");
    				continue;
    			}
    
    
    		} else {
    			continue;
    		}
    
    
    		break;
    	}
    
    }

    Code tags fixed by Hammer

  2. #2
    venus
    Guest

    oops

    i'm sorry. the code tags didnt work?

  3. #3
    Registered User
    Join Date
    Nov 2002
    Posts
    491
    Code tags have [] around them not <>.

    fgets() is not a replacement for scanf, it is a replacement for gets. It just reads a string in, no formatting. Try using fgets to read it in then sscanf to read from the string. It is a bit safer than just using scanf.

  4. #4
    Me want cookie! Monster's Avatar
    Join Date
    Dec 2001
    Posts
    680
    Code:
    char buf[BUFSIZ]; /* BUFSIZ is defined in stdio.h */
    
    printf("Enter date (YYYY MM DD): ");
    
    if(fgets(buf, BUFSIZ, stdin) == NULL)
    {
       ... /* error handling */
    }
    else
    {
       i = sscanf(buf, "%d %d %d", yyyy, mm, dd);
       ...
    }

  5. #5
    venus
    Guest
    thanx for fixing the code tags

    is there anyway to do it without using sscanf either? i'm not trying to be a pain, but then it's part of the specs. please give me some clues and i'll try to work on it? thanx again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fgets not working after fgetc
    By 1978Corvette in forum C Programming
    Replies: 3
    Last Post: 01-22-2006, 06:33 PM
  2. problem with fgets
    By learninC in forum C Programming
    Replies: 3
    Last Post: 05-19-2005, 08:10 AM
  3. problem with fgets
    By Smoot in forum C Programming
    Replies: 4
    Last Post: 12-07-2003, 03:35 AM
  4. fgets crashing my program
    By EvBladeRunnervE in forum C++ Programming
    Replies: 7
    Last Post: 08-11-2003, 12:08 PM
  5. help with fgets
    By Unregistered in forum C Programming
    Replies: 2
    Last Post: 10-17-2001, 08:18 PM