I am working in a program that have to read user input (last name, first name, and score) and write this information in a text file. I created one loop that prompts for the input and set flags for each input right. the loop should end when all input is collected and the user doesn't want to add nothing else.
The problem is that I set variables to hold the names, but I need one way to reuse these variables for the next iterations of the loop. So, the loop starts, collects user input, write to the file, and then it should "clear" the variables for the new iteration.
The user should be able to insert as much data as possible in the file. But right now, I just can add one set of data: (last name, first name, and score).
void enter_data(void)
{
/* create file */
FILE *fp;
/*variables*/
char answer;
int flag1 = 0;
int flag2 = 0;
int flag3 = 0;
int score = 0;
int test;
char leave[SIZE] = "exit";
char input_lname[SIZENAME];
char input_fname[SIZENAME];
char input_score[5];
char input_answer[5];
char lname[SIZENAME];
char fname[SIZENAME];
/*check if file was created */
if((fp = fopen("students.dat", "ab+")) == 0){
perror("fopen");
}
/* start of interaction */
while(!(flag1 && flag2 && flag3))
{
flag1 = 0;
flag2 = 0;
flag3 = 0;
/* ask for last name */
while(flag1 != 1)
{
printf("Enter last name:\n");
if(!fgets(input_lname, SIZENAME, stdin))
{
clearerr(stdin);
break;
}
/* validate last name. if not digit... */
if(!sscanf(input_lname, "%d", &test) == 1)
/*put first word in lname */
sscanf(input_lname, "%16s", lname);
if(strcmp(input_lname, leave) != 0)
{
flag1 = 1;
break;
}
}
/* ask for first name */
while(flag2 != 1)
{
printf("Enter first name:\n");
if(!fgets(input_fname, SIZENAME, stdin))
{
clearerr(stdin);
break;
}
/* validate first name. if not digit... * */
if(!sscanf(input_fname, "%d", &test ) == 1)
{
/*put first word in fname */
sscanf(input_fname, "%16s", fname);
flag2 = 1;
break;
}
}
/* ask for score */
while(flag3 != 1)
{
printf("Enter score:\n");
if(!fgets(input_score, SIZENAME, stdin))
{
clearerr(stdin);
break;
}
/* validate last name */
if(sscanf(input_score, "%3d", &score) == 1)
{
if((score >= 0) && (score <= 100))
{
flag3 = 1;
break;
} else if (score == -1)
break;
}
}
/* store record in file */
if((flag1 == 1) && (flag2 == 1) && (flag3 == 1))
{
printf("r %16s, %16s, %5d", lname, fname, score);
fprintf(fp, "%16s %16s %5d", lname, fname, score);
}
/* ask for another student */
printf("Would you like to enter data for another student?\n");
if(!fgets(input_answer, SIZE, stdin))
{
clearerr(stdin);
break;
}
if(sscanf(input_answer, "%s", &answer) == 1)
{
if(answer == 'y')
{
flag1 = 0;
flag2 = 0;
flag3 = 0;
continue;
} else
break;
}
flag1 = 0;
flag2 = 0;
flag3 = 0;
fclose(fp);
/* finish asking */
}
}