-1

C ++を使用して、fgetsを使用してテキストファイルをchar配列に読み込んでいます。次に、この配列内のすべての要素のインデックスを取得します。つまり、line [0] = 0.54 3.25 1.27 9.85、次に行のすべての要素を返します。別の配列の[0]、つまりreadElement [0]=0.54。私のtext.txtファイルの形式は次のとおりです。0.543.251.279.85 1.23 4.752.913.23これが私が書いたコードです。

char line[200]; /* declare a char array */
char* readElement [];

read = fopen("text.txt", "r");
while (fgets(line,200,read)!=NULL){ /* reads one line at a time*/
printf ("%s print line\n",line[0]); // this generates an error

readElement [n]= strtok(line, " "); // Splits spaces between words in line
    while (readElement [1] != NULL)
  {
printf ("%s\n", readElement [1]); // this print the entire line not only element 1

  readElement [1] = strtok (NULL, " ");
  }
n++;
}

ありがとう

4

1 に答える 1

0

readElement が誤って宣言されているようです。文字列の先頭へのポインターとして宣言するだけです。

char* readElement = NULL;

fopen からの戻り値もチェックしていません。それが最も可能性の高い問題です。したがって、ファイルが実際に開かれなかった場合に printf に渡すと、「行」はゴミになります。

行の各要素を実際に配列に格納する場合は、メモリを割り当てる必要があります。

また、変数に「read」という名前を付けないでください。「read」は、下位レベルの関数の名前でもあります。

const size_t LINE_SIZE = 200;
char line[LINE_SIZE];
char* readElement = NULL;
FILE* filestream = NULL;

filestream = fopen("text.txt", "r");
if (filestream != NULL)
{
    while (fgets(line,LINE_SIZE,filestream) != NULL)
    {
        printf ("%s print line\n", line);

        readElement = strtok(line, " ");
        while (readElement != NULL)
        {
             printf ("%s\n", readElement);
             readElement = strtok (NULL, " ");    
        }
      }
    }
    fclose(filestream);
}
于 2012-04-22T06:46:01.410 に答える