Thread: program ignoring fgets/scanf!

  1. #1
    template<typename T> threahdead's Avatar
    Join Date
    Sep 2002

    program ignoring fgets/scanf!

    i read some about a challenge in C and coded it in a matter of minutes.
    the exercise was:
    Write a complete program that will ask for a person's name and his or her game score. Then it will ask for a second person's score. The program will print the winner's name and also print by how many points that person won.
    heres my code
    #include <stdio.h>
    int main()
    	struct data
    		char name[256];
    		int score;
    	} names[2];
    	printf("enter the first name: ");
    	fgets(names[1].name, sizeof(names[1].name), stdin);
    	printf("enter the first score: ");
    	scanf("%d", &names[1].score);
    	printf("enter the second name: ");
    	fgets(names[2].name, sizeof(names[2].name), stdin);
    	printf("enter the second score: ");
    	scanf("%d", &names[2].score);
    	if(names[1].score < names[2].score)
    		printf("the winner is: ");
    		printf("%s\n", names[2].name);
    		printf("he won by %d points", names[2].score-names[1].score);
    		printf("the winner is: ");
    		printf("%s\n", names[1].name);
    		printf("he won by %d points", names[1].score-names[2].score);
    	return 0;
    why is the second fgets/scanf statement ignored by my program?

  2. #2
    Registered User
    Join Date
    Dec 2002
    Its because the '\n' character.
    Fgets dont read the line character, leaves it. So
    next time when scanf starts to read it finds the '\n' char first and stop reading.
    After fgets, test if '\n' was read, otherwise clean it from the buffer.
    Like this

    "Can i really learn this? If i cant, why bother?"

  3. #3
    template<typename T> threahdead's Avatar
    Join Date
    Sep 2002
    thanks for that quick answer!

  4. #4
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Better still, don't mix your use of scanf() and fgets(). Best to read all the input with fgets() and perform any necessary conversion (char to number) internally.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  5. #5
    template<typename T> threahdead's Avatar
    Join Date
    Sep 2002
    how would i read a number with fgets?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Issue with program that's calling a function and has a loop
    By tigerfansince84 in forum C++ Programming
    Replies: 9
    Last Post: 11-12-2008, 01:38 PM
  2. Need help with a program, theres something in it for you
    By engstudent363 in forum C Programming
    Replies: 1
    Last Post: 02-29-2008, 01:41 PM
  3. Replies: 4
    Last Post: 02-21-2008, 10:39 AM
  4. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  5. My program, anyhelp
    By @licomb in forum C Programming
    Replies: 14
    Last Post: 08-14-2001, 10:04 PM