関数をデバッグしましたが、機能しています。そうそう、Cの独学は順調に進んでいるようです。しかし、私はそれをより良くしたいです。つまり、次のようなファイルを読み取ります。
want
to
program
better
そして、文字列の個々の行を文字列の配列に入れます。ただし、印刷すると奇妙になります。私が読んだ限りでは、strcpy() は \0 文字まで文字列をコピーするだけです。それが本当なら、なぜ次は文字列 want と \n を出力するのですか? strcpy() も \n をコピーしたようで、そこにぶら下がっています。私はそれを取り除きたいです。
ファイルをコピーするための私のコードは以下のとおりです。起こっていることに関連しているとは思えないので、プログラム全体を含めませんでした。私は問題がここにあることを知っています。
void readFile(char *array[5049])
{
char line[256]; //This is to to grab each string in the file and put it in a line.
int z = 0; //Indice for the array
FILE *file;
file = fopen("words.txt","r");
//Check to make sure file can open
if(file == NULL)
{
printf("Error: File does not open.");
exit(1);
}
//Otherwise, read file into array
else
{
while(!feof(file))//The file will loop until end of file
{
if((fgets(line,256,file))!= NULL)//If the line isn't empty
{
array[z] = malloc(strlen(line) + 1);
strcpy(array[z],line);
z++;
}
}
}
fclose(file);
}
だから今、私が次のことをするとき:
int randomNum = rand() % 5049 + 1;
char *ranWord = words[randomNum];
int size = strlen(ranWord) - 1;
printf("%s",ranWord);
printf("%d\n",size);
int i;
for(i = 0; i < size; i++)
{
printf("%c\n", ranWord[i]);
}
次のように出力されます。
these
6
t
h
e
s
e
代わりに次を出力するべきではありませんか?
these6
t
h
e
s
e
したがって、私が理解できる唯一のことは、文字列を配列に入れると、\nもそこに入れられるということです。どうすればそれを取り除くことができますか?
いつものように、敬意を表して。オタクオメガ