So I have written some code that has a switch
, and I need to give it an integer to select a case
within the switch
. I can't use scanf()
because I have multiple fgets()
further down the line and the '\n'
from the scanf()
input breaks the code.
Here is my code:
main.c
#include "functions.h"
#include <stdlib.h>
int main() {
int choice;
char temp[10];
do {
printf("Menu\n\n");
printf("1. Read student information from file\n");
printf("2. Write student information to file\n");
printf("3. Exit\n");
fgets(choice, 10, stdin);
switch (choice) {
case 1:
fileRead();
break;
case 2:
fileWrite();
break;
default:
printf("Program stopped!\n");
break;
}
} while (choice != 3);
return 0;
}
functions.h
#ifndef UNTITLED17_FUNCTIONS_H
#define UNTITLED17_FUNCTIONS_H
#include <stdio.h>
#include <string.h>
struct student {
char studentID[100];
char studentName[100];
char age[100];
} student_t;
void fileRead() {
FILE *f = fopen("student_read.txt", "r");
if (f == NULL) {
printf("Failed to open file(s)!\n");
}
printf("Type your student ID:");
fgets(student_t.studentID, 100, stdin);
printf("Type your name:");
fgets(student_t.studentName, 100, stdin);
printf("Type your age:");
fgets(student_t.age, 100, stdin);
printf("Student id: %s\n", student_t.studentID);
printf("Name: %s\n", student_t.studentName);
printf("Age: %s\n", student_t.age);
}
void fileWrite() {
FILE *f = fopen("student_write.txt", "w");
if (f == NULL) {
printf("Failed to open file(s)!\n");
}
printf("Type your student ID:");
fgets(student_t.studentID, 100, stdin);
printf("Type your name:");
fgets(student_t.studentName, 100, stdin);
printf("Type your age:");
fgets(student_t.age, 100, stdin);
printf("Student id: %s\n", student_t.studentID);
printf("Name: %s\n", student_t.studentName);
printf("Age: %s\n", student_t.age);
}
#endif //UNTITLED17_FUNCTIONS_H
Any ideas?
Thanks :)