c - 学生信息文件处理

标签 c

你能帮我改进我的代码吗……这都是关于学生信息的……我在语法上有问题……在编辑菜单中……我尝试使用 strcmp 但没有任何反应,我首先使用 fgets并将其存储在一个数组中,然后要求用户输入并将其再次存储在另一个数组中..然后我会比较......但它没有用..希望你能帮助我......这是我的代码..

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

struct student{
       char name[30];
       char id[8];
       char course[5];
};

int main(void){
    int option =0;

    while(option!=6){
       system("cls");
       printf("Menu:\n");
       printf("[1] Add Student.\n");
       printf("[2] Display Student.\n");
       printf("[3] Delete Student.\n");
       printf("[4] Delete Student.\n");
       printf("[5] Exit.\n");
       scanf("%d",&option);

       switch(option)
       {
          case 1:
                addStudent();
                break;
          case 2:
                displayinfo();
                break;
          case 3:
                break;  
          case 4:
                break;
          default:
                printf("That is not in the options!\nPlease Try again!\n");
                break;
       }

    }
}

addStudent(){
    int i;
    FILE *stream = NULL;
    stream = fopen("studentinfo.txt", "a+");

    struct student s1;
    struct student array[3];//here i wnt 2 apply d malloc but, still didn't know how 2start
    for (i =0; i<1; i++){

       printf("Enter Student ID: ");
       scanf("%s", s1.id);
       fflush(stdin);
       printf("Enter Student Name: ");
       gets(s1.name);
       fflush(stdin);
       printf("Enter Student Course: ");
       scanf("%s", s1.course);

       fprintf(stream, "\n%s,\t%s,\t%s", s1.id, s1.name, s1.course);
    }
       fclose(stream);
    getch();
}
displayinfo(){
    FILE *stream = NULL;
     stream = fopen("studentinfo.txt", "rt");

     char arr[100];
     int i=0;

    while(!feof(stream)){  
     fgets(arr, 100, stream);
     printf("%s", arr);
     }

     fclose(stream);
     getch();
}

这是我在编辑菜单中的计划:

     printf("enter details: ");
     gets(arr2);

     while(!feof(stream)){ 
        fgets(arr, 100, stream);
        if(strcmp(arr, arr2)==0){
           //code here
        }

     }

这行得通吗?

谢谢你们希望你们能帮助我^_^

最佳答案

fgets() 保留换行符。 gets() 没有。因此字符串永远不会匹配。

如果您不能完全确定某个功能在做什么,请尝试阅读该功能的手册。

尝试使用 fgets(arr2, 100, stdin) 而不是 gets(arr2)

关于c - 学生信息文件处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4344776/

相关文章:

python - C : What assumptions can be made about the value of the underlying variable? 中的枚举

c - C中的算术运算给出奇怪的值

c - C 中的结构元素排序

c - 如何通过命名管道(fifo)传输结构的内容?

c - 为什么这个 switch case 程序在整数输入之后不接受字符输入?

创建一个空结构

c - 程序启动前valgrind奇怪的条件跳转信息

c++ - 使用 qsort 对 2D 数组进行排序 - 正确的类型转换

c - C中通过JTAG读取STM32L4闪存

c - 当我使用 -static 时 GCC 吓坏了