【发布时间】:2022-01-09 07:08:26
【问题描述】:
所以我编写了一些具有switch 的代码,我需要给它一个整数以在switch 中选择case。我不能使用scanf(),因为我有多个fgets(),而且scanf() 输入中的'\n' 会破坏代码。
这是我的代码:
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
有什么想法吗?
谢谢:)
【问题讨论】:
-
使用
fgets和sscanf缓冲区,然后其他fgets调用将按预期工作。 -
不要将函数定义放入
h文件中。它仅用于声明(原型)。 -
编译器没有抱怨
fgets(choice, 10, stdin);? -
没有什么可以阻止您使用
scanf,但您需要正确使用它。如果您想使用换行符,scanf("%d",...)不会这样做,但没有什么可以阻止您以其他方式使用它。 (例如,循环调用fgetc) -
@Ole-Johan 不过,恭喜您发现了
scanf/fgets隔行扫描问题。我们每天都会收到几十个问题,询问为什么fgets不起作用。这是我记得第一次看到一个已经知道这个问题并试图做得更好的人提出的问题。