Weird Loop

Jan 28, 2008 at 12:14pm
Hi, I am having problems with this code. It doesn't allow me to key in data for student 1. Jumps straight to Student 2 and Student 3.

Output I am getting:

How many people in the group [1 to 20]? 3
Enter name for student 1: Enter name for student 2: john
Enter name for student 3: jill



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#define MAXSIZE 20
#define MAXLEN 30

int main(void)
{
	char name[MAXSIZE][MAXLEN];
	int i, size;

	printf("How many people in the group [1 to %d]? ", MAXSIZE);
	scanf("%d", &size);
		
	for(i=0; i<size; i++)
	{
		printf("Enter name for student %d: ", i+1);
 		fgets(name[i], MAXLEN+1, stdin);
	} //end for

}//end main
Last edited on Jan 28, 2008 at 4:45pm
Jan 28, 2008 at 7:09pm
The problem is not in the loop.

The call to "scanf" reads an integer from the input but leaves the RETURN character in the buffer, so the first time gets is executed, you get an empty line.

A good approach to user input is to always get whole lines and then retrieve whatever data you want from the extracted lines. For example, you could replace your call to scanf by:

1
2
3
char buffer[MAXLEN];
fgets(buffer,MAXLEN,stdin);
sscanf (buffer,"%d",&size);
Jan 28, 2008 at 11:01pm
Thanks understood.
Topic archived. No new replies allowed.