2013-12-12 113 views
-1

嘿夥計們在這裏處理代碼,我有點不知所措。在txt文件中查找字符串並顯示一行

int main() 
{ 

    FILE *fp; 
    struct info 
    { 
     char name[15]; 
     char surename[15]; 
     char gender[15]; 
     char education[15]; 

    } info; 

    char c; 
    int i, j, a; 
    struct info sem; 

    beginning: 

    scanf("%d", &a); 

if(a==1) 
{ 
fp = fopen("info.txt", "r"); 
    for(i=0;!feof(fp);i++) 
{ fscanf(fp, "%s %s %s %s", 
       sem.name, 
       sem.surname, 
       sem.gender, 
       sem.education,); 
       printf("%s, %s, %s, %s\n", 
       sem.name, 
       sem.surname, 
       sem.gender, 
       sem.education,); 
    } 
     fclose(fp); 
    goto beginning; 
    } 
    if (a == 2) 

    { 
     FILE *fp = fopen("info.txt", "r"); 
     char tmp[256] = { 0x0 }; 
     while (fp != NULL && fgets(tmp, sizeof(tmp), fp) != NULL) 

     { 

      if (strstr(tmp, "bachelors")) 

       /* Code works fine until this part */ 

       fprintf(fp, "\n%s %s %s %s %s %s", 
         sem.name, sem.surname, sem.gender, sem.education,); 

     } 
     if (fp != NULL) 
      fclose(fp); 
     goto beginning; 
    } 

找到字符串後「光棍」應該在printf線的其餘部分在那裏發現了它,在這種情況下名字,姓氏等,大學本科學歷找到用戶等,但它不,如果任何人都可以指出我的錯誤,編號非常偉大!

+2

它看起來像你沒有分配任何東西到'sem',但你打印'sem'成員期望它包含的東西。 – lurker

+0

不,不是可怕的'goto'! –

+0

抱歉設法忘記添加該代碼部分 – user3043290

回答

0

執行以下操作:在結構 2.在您的代碼擺脫GOTO 1.修訂(它是一個不好的編程標準) 3.正確的代碼縮進

通過下面的代碼

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

int main() 
{ 
    struct info 
    { 
     char name[15]; 
     char surname[15]; 
     char gender[15]; 
     char education[15]; 

    } sem; 

    FILE *fp=NULL; 
    int i, a; 
    char tmp[256] = {0x0}; 

    while(1) 
    { 
     printf("Enter the value\n"); 
     scanf("%d", &a); 

     if((fp = fopen("info.txt", "r")) != NULL) 
     { 

      switch(a)  // assuming your code is just an snippet and actual code has more than 2 conditions 
      {    // use if-else if just 2 condition checks 

       case 0: 
         exit(0);  // quit the program 

       case 1: 

        for(i=0;!feof(fp);i++) 
        { 
         fscanf(fp, "%s %s %s %s", sem.name, sem.surname, sem.gender, sem.education); 
         printf("%s, %s, %s, %s\n",sem.name,sem.surname,sem.gender,sem.education); 
        } 

        break; 

       case 2: 

        while (fgets(tmp, sizeof(tmp), fp) != NULL) 
        { 
         if (strstr(tmp, "bachelors")) 
         { 
          /* Code works fine until this part */ 
          fprintf(fp, "\n%s %s %s %s", sem.name, sem.surname, sem.gender, sem.education);       
         } 
        } 

        break; 

       default: printf("Default statement");           
      } 

      fclose(fp); 

     } 
    } 
} 
+0

'while(fgets(tmp,sizeof(tmp),fp)!= NULL)'也似乎不需要你可以只做一個'fgets'並繼續 – nimish

相關問題