2016-12-06 58 views
1
void menu() { 
    int op; 
    printf("\n Choose a option from below : \n\n"); 
    printf(" 1: Add Contact\n" 
      " 2: View A Contact\n" 
      " 3: View All Contacts\n" 
      " 4: View All Contacts With a Common First Character\n" 
      " 5: Delete All Contact\n" 
      " 6: Delete A Contact\n" 
      " 7: Replace A Contact Name\n" 
      " 8: Replace A Contact Number\n" 
      " 9: Refresh\n" 
      " 10: Exit\n\n"); 

    printf(" Which one ? "); 
    fgets(op, 5, stdin); 

    switch ((int)op) { 
    case 1: addrecords(); break; 
    case 2: viewone(); break; 
    case 3: viewall(); break; 
    case 4: viewonechar(); break; 
    case 5: deleteall(); break; 
    case 6: deleteone(); break; 
    case 7: replaceone(); break; 
    case 8: replaceonenumber(); break; 
    case 9: refresh(); break; 
    case 10: exit(0); break; 

    default: 
     printf ("\n Wrong Option.\n\n"); 
     menu(); 
     break; 
    } 
} 

void addrecords() { 
    char name[50]; 
    char number[20]; 

    printf("\n\n Enter Contact Number (+880) : "); //Skips this 
    fgets(number, 20, stdin); 

    check(number); 

    printf(" Enter Contact Name : "); //Comes in here 
    fgets(name, 50, stdin); 

    fp = fopen("Phonebook.txt","a"); 

    fprintf(fp, "%s %s\n", name, number); 

    fclose(fp); 

    printf("\n Contact Successfully Saved!\n Returning To Main Menu...\n\n"); 

    menu(); 
} 

void check(char n[20]) { 
    char name[25]; 
    char ncheck[20]; 

    fp = fopen("Phonebook.txt", "r"); 
    fscanf(fp, "%s %s", name, ncheck); 

    while (!feof(fp)) { 
     if ((strcmp(ncheck, n)) == 0) { 
      printf ("\n Contact Already Exists.\n\n"); 
      fclose(fp); 
      menu(); 
     } else { 
      fscanf (fp, "%s %s", name, ncheck); 
     } 
    } 
} 

好吧我編輯了我的程序。我輸入1後,程序說錯了選項。但我正在寫入一個。雖然我做得對,但爲什麼程序顯示錯誤的選項?這是否與fgets?現在有什麼問題?scanf和fgets在同一個程序中

+0

沒有辦法讓scanf不留任何換行符嗎? –

+0

我的建議:不要使用'scanf',而是用你需要寫的函數替換它,比如'int GetInteger()'。使用''fgets''(http)替換'scanf('%d',&op);'''GetInteger()'''GetInteger()'函數非常容易編寫~3-4行代碼。 ://www.cplusplus.com/reference/cstdio/fgets/)和['atoi'](http://www.cplusplus.com/reference/cstdlib/atoi/) –

+0

請看[Why is「while( !(feof(file))「總是錯?](http://stackoverflow.com/q/5431941/2173917) –

回答

2

那麼,試圖改變你的程序,至少我可以不指出其他錯誤或缺乏錯誤檢查...並儘量保持它儘可能簡單,以瞭解發生了什麼,你需要什麼做的是替換:

switch ((int)op) { 

的東西,如

switch (atoi(op)) { 

(或創建自己的get_int()結合fgets()strtol()sscanf()