why this works?

Started by
0 comments, last by pjstirling 19 years, 7 months ago
sorry, i may have made a cross-post: but i finally got the program work with this code:

#define BUFFERMAXSIZE 80
struct record{
	char name[20];
	char student_id[7];
	char class_id[4];
	char position[25];
};

int input_data()
{

	FILE *output_file;
	output_file = fopen("results.txt", "a+");

	struct record student;
	
	char ch;

	char buffer[BUFFERMAXSIZE];
	

	fflush (stdin);
 //data ==> output_file
	printf("Name: ");
	gets(student.name);
	strcat(student.name, "\n");

	printf("Class: ");
	gets(student.class_id);
	strcat(student.class_id, "\n");

	printf("Student ID: ");
	gets(student.student_id);
	strcat(student.student_id, "\n");
	
	printf("Position: ");
	gets(student.position);
	strcat(student.position, "\n");

	printf("Are you sure to add new member/change member information(Y/N)? ");
	ch = getchar();
	ch = toupper(ch);
	if( ch == 'Y' )
	{
		fputs(student.name,output_file);
		fputs(student.class_id, output_file);
		fputs(student.student_id, output_file);
		fputs(student.position, output_file);
		fclose(output_file);
		input_screen();
	}
	else if( ch == 'N'){
		return 0;
		fclose(output_file);
	}
	else{
			printf("\nInvalid Choice, Please try again");
			fclose(output_file);
	}
	printf("\n");
	
}


but why it doesn't work with this thingy::::::



int input_data()
{

	FILE *output_file;
	output_file = fopen("results.txt", "a+");

	struct record student;
	
	char ch;

	char buffer[BUFFERMAXSIZE];
	

	fflush (stdin);
 //data ==> output_file
	printf("Name: ");
	gets(buffer);
	strcpy(student.name, buffer);
	strcat(student.name, "\n");

	fflush (stdin);

	printf("Class: ");
	gets(buffer);
	strcpy(student.class_id, buffer);
	strcat(student.class_id, "\n");

	printf("Student ID: ");
	gets(buffer);
	strcpy(student.student_id, buffer);
	strcat(student.student_id, "\n");
	
	printf("Position: ");
	gets(buffer);
	strcpy(student.position, buffer);
	strcat(student.position, "\n");

	printf("Are you sure to add new member/change member information(Y/N)? ");
	ch = getchar();
	ch = toupper(ch);
	if( ch == 'Y' )
	{
		fputs(student.name,output_file);
		fputs(student.class_id, output_file);
		fputs(student.student_id, output_file);
		fputs(student.position, output_file);
		fclose(output_file);
		input_screen();
	}
	else if( ch == 'N'){
		return 0;
		fclose(output_file);
	}
	else{
			printf("\nInvalid Choice, Please try again");
			fclose(output_file);
	}
	printf("\n");
	
}


is that one more null character exist inside the buffer????pls reply my question
Advertisement
I can't see anything particularly wrong with it (I presume the main difference between the two is that you read into the buffer and then copy the string into the student record)

Why are you flushing stdin each time? It shouldn't be necessary for what you are doing.

What exactly is going wrong (and where)?

This topic is closed to new replies.

Advertisement