2010-12-03 7 views
1

私のコードを改善するのに役立つことができます...これは学生情報に関するすべてです...私は構文に問題があります...編集メニューで...私は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 
     } 

    } 

意志この作品は?

おかげでみんながあなたが私を助けることができると思います^ _^

+1

をハングアップすることがありますので、エラーは表示されませんこれはあなたの宿題ですか?あなたの質問に家事用のタグをつけて – fardjad

+2

それがうまくいくかどうかを尋ねる前に、自分でコードを実行しようとしましたか? –

+0

プログラム全体が実行されています...既に学生情報を追加して表示しています...私は編集と削除に問題があります...あなたが私を助けることを願っています:) – iamanapprentice

答えて

3

のfgets()は改行を維持します。 gets()はしません。したがって、文字列は決して一致しません。

何をしているのかが完全にわからない場合は、機能のマニュアルをお読みください。

gets(arr2)の代わりにfgets(arr2, 100, stdin)を実行してください。

+0

うわー...私は何かを学んだ。 :) thanks @AlastairG – newbie

+0

ようこそ。空の矢印をクリックして答えを受け取り、恐らくこれが良い答えだと思っていることを示すために0の上にある上向きの矢印をクリックしてください。 :) – AlastairG

+0

毎日の投票限度に達しました。私は明日それをクリックします – newbie

1
while(!feof(stream)){ 
    fgets(arr, 100, stream); 

使用

while(fgets(arr, 100, stream) != NULL) { 
    ... 
} 

if (ferror(stream)) 
    printf("error in file" "\n"); 

はfeof()読みながら、それはループ