2016-10-26 4 views
0

ファイルの内容を2つの別々の種類に分けて読み込もうとしています。これを以下に示します。ファイル内のデータを区別するC

# Type names 
bird 
mammal 
reptile 
. 
# Type effectiveness 
Very_effective 
Not_effective 
. 

これまでのところ私は、第1のタイプの内容を読み取ることができますが、私は2番目の内容を読み取るしようとしたとき、私は最初の再読み込みの内容に保ちます。私は最初の効果の種類をプリントアウトしてみ瞬間

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

int main() { 
    typedef struct 
    { 
     char types[1000]; 
     char effectiveness[1000]; 
    } sinFile; 
    sinFile record[1000]; 

    FILE* file; 
    char line[121]; 
    char period[10]; 
    char hash[10]; 

    char* item; 
    char* item2; 
    int i = 0; 
    int j = 0; 

    file = fopen("Test.txt", "r"); 

    while(fgets(line, 120, file)) { 
     item = strtok(line, " "); 
     strcpy(period, "."); 

     if (item[0] == '#') { 
      continue; 
     } else { 
      do { 
       strcpy(record[i].types, line); 
       i++; 
      } while (strcmp(record[i].types, period) == 0); 
     } 
     item2 = strtok(line, " "); 
     if (item2[0] == '#') { 
      continue; 
     } else { 
      do { 
       strcpy(record[j].effectiveness, line); 
       j++; 
      } while (strcmp(record[j].effectiveness, period)== 0); 
     } 
    } 

    fclose(file); 

    printf("%s", record[0].effectiveness); 
} 

は、それは鳥など

私は近いですが、私はprocede方へとわからないように私は感じをプリントアウト。

答えて

0

strtok()の問題があります。マンページから:

strtok()関数は、文字列を一連のトークンに解析します。 strtok()への最初の呼び出しでは、解析される文字列はstrtokに指定されるべきです。後続の各呼び出しで、同じ文字列を解析する必要があります。strはNULLにする必要があります。 strを解析することを意味し

、最初strtok(str, " ")としてそれを呼び出す必要があり、さらに文字列を解析するために、あなたはstrtok(NULL, " ")としてそれを呼び出す必要があります。 2度目にstrtok(str, " ")と呼び出すと、strの先頭から再び開始されます。

関連する問題