【问题标题】:How can I perfectly truncate a string in c?我怎样才能完美地截断c中的字符串?
【发布时间】:2015-03-01 11:34:02
【问题描述】:

我正在读取每行长度超过 63 个字符的文件,我希望将字符截断为 63。但是,它无法截断从文件中读取的行。

在这个程序中,我们假设文件只有 10 行:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char a[10][63];
    char line[255];

    int count = 0;

    //Open file                
    FILE *fp;
    fp = fopen("lines.dat", "r"); 

    //Read each line from file to the "line array"
    while(fgets(line, 255,fp) != NULL)
    {
        line[63] = '\0';

        //copy the lines into "a array" char by char
        int x;
        for(x = 0; x < 64; ++x)
        {
            a[count][x] = line[x];
        }

        count++;
    }

    fclose(fp);

    //Print all lines that have been copied to the "a array"
    int i;
    for(i = 0; i < 10; i++)
    {
        printf("%s", a[i]);
    }


}

【问题讨论】:

  • 您需要包含空字符:for (x = 0; x &lt; 21; x++)
  • 我应该把角色放在哪里。请原谅我是 C 的新手。谢谢@grc
  • 按照@grc 的建议使用for (x = 0; x &lt; 21; x++)
  • strncpy (a[0], line, 20); - 使用 \0 和 for 循环省去麻烦。
  • 如果你只想要 63 个字符,为什么不让 fgets 来做呢? fgets(a[i++], 63 , fp)

标签: c arrays string char truncate


【解决方案1】:

你得到这个结果是因为你忘记在 a[0] 的末尾添加空字符串终止符。

有几种方法可以做到这一点。我最喜欢的是保持原样:因为您似乎想要在其他地方截断字符串,所以您不需要修改源代码。 在这种情况下,您可以替换:

//Tries to truncate "line" to 20 characters
line[20] = '\0';

//copying line to each character at a time
int x;
for(x = 0; x < 20; x++)
{
    a[0][x] = line[x];
}

//copying line to each character at a time
int x;
for(x = 0; x < 20; x++)
{
    a[0][x] = line[x];
}
a[0][20] = 0;

【讨论】:

    【解决方案2】:

    我认为您缺少空字节。

    您可以通过以下方式获得更多信息:Null byte and arrays in C

    【讨论】:

    • 您应该将此作为评论发布,而不是作为答案发布。如果您希望这成为答案,请在帖子中进行解释,而不仅仅是提供链接。
    猜你喜欢
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 2016-05-10
    • 2015-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    相关资源
    最近更新 更多