我调试了一个功能,它正在工作。所以,耶稣教导我自己似乎很顺利。但我想让它变得更好。也就是说,它读取一个像这样的文件:为什么strcpy()也在复制 n?我可以摆脱它吗?
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放在那里。我怎样才能摆脱这一点?
一如既往,尊重。 GeekyOmega
是'\ n' =='\ 0',如果不是,则复制。简单。如果你想避免这种情况,写你自己的'strcpy()'。或者如果换行符总是在末尾,则操作'\ 0'字符位置。 – jn1kk 2012-07-31 15:42:16
请勿使用feof();你不需要它,如果你不需要在错误和EOF之间做出区别。把fgets()放在循环里就够了,而且简单得多。 – wildplasser 2012-07-31 16:48:20
我认为这是封闭的。感谢所有回答。 – GeekyOmega 2012-08-07 16:03:27