(Cで)配列に格納する私は、以下からなる入力ファイルがあります。読書スペース区切り文字列のラインごととは
CREATEHALL "Red-Hall" "StarDust" 24 20
CREATEHALL "Orange-Hall" "Last_Samurai" 10 20
をそして私は、将来の使用のために、アレイ内の各ラインを保存したいです。
は、これまでのところ、私のコードは次のとおりです。 (デバッグ目的のためのprintfのをたくさん追加しました)
#include <stdio.h>
#include <stdlib.h>
struct str
{
char *commands[5];
};
struct str a[];
int main()
{
int i=0;
int j=0;
char *token;
printf("Starting the program...\n");
char filename[] = "input.txt";
FILE *file = fopen (filename, "r");
if (file != NULL) {
char line [1000];
printf("Read a new line...\n");
while(fgets(line,sizeof line,file)!= NULL) /* read a line from a file */ {
j=0;
printf("%s\n",line);
printf("Start token stuff...\n");
/* get the first token */
token = strtok(line, " ");
/* walk through other tokens */
while(token != NULL)
{
a[i].commands[j]=token;
printf("Stored Command : %s\n", token);
token = strtok(NULL, " ");
j++;
}
i++;
}
fclose(file);
}
else {
perror(filename); //print the error message on stderr.
}
printf("Finished processing tokens...\n\n\n");
printf("%s\n%s\t%s\t%s\t%s\n", a[0].commands[0], a[0].commands[1],a[0].commands[2],a[0].commands[3],a[0].commands[4]);
printf("%s\n%s\t%s\t%s\t%s\n", a[1].commands[0], a[1].commands[1],a[1].commands[2],a[1].commands[3],a[1].commands[4]);
return 0;
}
私はコンソールに乗る出力はこれです:
Starting the program...
Read a new line...
CREATEHALL "Red-Hall" "StarDust" 24 20
Start token stuff...
Stored Command : CREATEHALL
Stored Command : "Red-Hall"
Stored Command : "StarDust"
Stored Command : 24
Stored Command : 20
CREATEHALL "Orange-Hall" "Last_Samurai" 10 20
Start token stuff...
Stored Command : CREATEHALL
Stored Command : "Orange-Hall"
Stored Command : "Last_Samurai"
Stored Command : 10
Stored Command : 20
Finished processing tokens...
CREATEHALL
"Orange-Hall" l" murai" ai"
CREATEHALL
"Orange-Hall" "Last_Samurai" 10 20
I Cとはあまりよくないです(これは課題のごく一部です)。しかし、私はそのエラーがこの部分にあると信じています。
a[i].commands[j]=token;
ライン、前にそれがうまく言葉を読み込むことから。
ありがとうございます。
あなたはコマンドのためにそう – LPs
行うには、[のstrdup](https://linux.die.net/man/3/strdup)を使用することができる[5]配列あなたはすべての要素のためのスペースを割り当てる必要があります。 mallocを使い、文字列をコピーするにはstrcpyを使用してください。値の割り当てを使わないでください –
デバッグ用にたくさんのprintfsを追加するのではなく、デバッガを使うべきです。 –