Gee*_*ega 1 c arrays printf strcpy
我调试了一个函数,它正在工作.所以,自己教C似乎也很顺利.但我想让它变得更好.也就是说,它读取这样的文件:
want
to
program
better
Run Code Online (Sandbox Code Playgroud)
并将每个单独的字符串行放入一个字符串数组中.然而,当我打印出来时,事情变得奇怪.据我所知,strcpy()应该只是复制一个字符串,直到\ 0字符.如果这是真的,为什么以下打印字符串需要和\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);
}
Run Code Online (Sandbox Code Playgroud)
所以现在,当我做以下事情时:
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]);
}
Run Code Online (Sandbox Code Playgroud)
打印出来:
these
6
t
h
e
s
e
Run Code Online (Sandbox Code Playgroud)
不应该打印出以下内容吗?
these6
t
h
e
s
e
Run Code Online (Sandbox Code Playgroud)
所以我唯一可以想到的是,当我将字符串放入数组时,它也将\n放在那里.我怎么能摆脱它呢?
一如既往,尊重.GeekyOmega
fgets同时读入\n,它是输入文件的一部分.如果你想摆脱它,做一些像:
int len = strlen(line);
if (len > 0 && line[len-1] == '\n') line[len-1] = '\0';
Run Code Online (Sandbox Code Playgroud)