Question

I am writing a program which would store the student record in file named 'new' on desktop. If there is no file named 'new' then it should create it first, so I have used an if statement. I have also put the whole code in a do while loop, so it should loop though the code again and again. Inside the do while I have used switch

  1. to write to file using fprintf

  2. code still not written( will add read function to it later on)

  3. To exit out of do while loop

but I am getting an error 'ch' undeclared (first use this fucntion)

How can I fix this program?

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

typedef struct
{
int *name;
int score;
}structure;

int main()
{
FILE *file= fopen("C://Users//Abhimanyu Aryan//Desktop//new.txt","r");
if(file==NULL)
{
FILE *file=fopen("C://Users//Abhimanyu Aryan//Desktop//new.txt","w");
}

//Loop through this
do
{
printf("\n1) Add record\n2) View Record\n3) Exit");

int ch;
printf("Enter your choice: ");
scanf("%i",&ch);

switch (ch)
{
    //case 1 will include write access to file on pressing 1
case 1:
    //name
    printf("Enter name: ");
    char name[30];
    scanf("%c", name);
    //score
    printf("Enter score: ");
    int score;
    scanf("%i", &score);
    //printing to file
    fprintf(file, "%c\t%i", name, score);
    break;

//case still not in use
case 2:
    break;

//case to exit
case 3:
    break;

}
}while(ch != 3);

fclose(file);
return 0;
}
Was it helpful?

Solution

ah... the problem may well be this line of code:

} while (ch != 3)

the ch variable is defined ONLY inside the do-while loop... I'd try to define it outside the loop and see if that helped

OTHER TIPS

You should initialize ch outside of do..while loop, that's the error

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top