c - 为什么 strcpy() 也在复制\n?我可以摆脱它吗?

标签 c arrays printf strcpy

我调试了一个函数,它正在运行。所以,是的,自学 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 放在那里。我怎样才能摆脱它?

一如既往,怀着敬意。 极客欧米茄

最佳答案

fgets 也读取 \n,它是您输入文件的一部分。如果您想摆脱它,请执行以下操作:

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

关于c - 为什么 strcpy() 也在复制\n?我可以摆脱它吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11743884/

相关文章:

c - C语言客户端服务器模型中的密码认证

c - 查找多个整数之间的最小值和最大值

c++ - 常量有多少分配空间?

javascript - 将对象从数组 A 移动到数组 B. Ramda.js

c - 需要帮助 : Unable to delete string from doubly linked list: C

php - 将大量 Excel 数据插入 MySQL 数据库

c++ - 如何将 'A' 之类的单个字符替换为 "10"之类的字符?

haskell - 为什么 Haskell 要求对 printf 的数字进行消歧,而不是对 show 进行消歧?

带有双数组的 Java System.out.format

c - 是否可以仅打印出 C 字符串的特定部分,而不制作单独的子字符串?