2012-07-31 179 views
1

我调试了一个功能,它正在工作。所以,耶稣教导我自己似乎很顺利。但我想让它变得更好。也就是说,它读取一个像这样的文件:为什么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

+3

是'\ n' =='\ 0',如果不是,则复制。简单。如果你想避免这种情况,写你自己的'strcpy()'。或者如果换行符总是在末尾,则操作'\ 0'字符位置。 – jn1kk 2012-07-31 15:42:16

+0

请勿使用feof();你不需要它,如果你不需要在错误和EOF之间做出区别。把fgets()放在循环里就够了,而且简单得多。 – wildplasser 2012-07-31 16:48:20

+0

我认为这是封闭的。感谢所有回答。 – GeekyOmega 2012-08-07 16:03:27

回答

7

fgets也读取\n,它也是你的输入文件的一部分。如果你想摆脱它,这样做:

int len = strlen(line); 
if (len > 0 && line[len-1] == '\n') line[len-1] = '\0'; 
+0

更好:'if(len> 0 && line [len-1] =='\ n')line [ - len] ='\ 0';' – wildplasser 2012-07-31 15:50:56

+0

感谢你们俩。这确实解决了这个问题。 fgets()是一个非常糟糕的方式来做到这一点?我可以避免这样的事情是我用fread()来代替吗? – GeekyOmega 2012-07-31 15:56:57

+0

'fread'具有相同的行为。您可以通过使用C以外的语言来避免此问题,该语言具有更高级的内置字符串/ io处理(python,Java,...)。 – 2012-07-31 16:22:32

1

当你读的第一线,比如,你实际上读的“想\ n”,因为换行符的一部分该线。所以你得到“想要\ n \ 0”。对于其他行也是如此(除了最后一行,除非文件最后有空行)。

+0

感谢您的帮助! – GeekyOmega 2012-07-31 18:16:31

相关问题