我怎样才能完美地截断在C字符串? [英] How can I perfectly truncate a string in c?

查看:206
本文介绍了我怎样才能完美地截断在C字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从一个文件,它的每一行是超过63个字符长阅读,我想角色在63.不过被截断,它无法截断行从文件中读取。

在这个计划中,我们假定该文件有10只行:

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;INT主要(无效)
{
    烧焦一个[​​10] [63];
    焦线[255];    诠释计数= 0;    //打开文件
    FILE * FP;
    FP = FOPEN(lines.dat,R);    //从文件中读取每一行的行阵
    而(与fgets(行,255,FP)!= NULL)
    {
        行[63] ='\\ 0';        //行复制到一个数组字符成炭
        INT X;
        为(X = 0; X&下; 64; ++ x)的
        {
            一个[计数] [X] =行[X];
        }        算上++;
    }    FCLOSE(FP);    //打印已复制到一个数组的所有行
    INT I;
    对于(I = 0; I&小于10;我+ +)
    {
        的printf(%S,一个[我]);
    }
}


解决方案

您有这样的结果,因为你忘了加空字符串结束在末尾的[0]

有几种方法可以做到这一点。我最喜欢的是离开行是:因为它似乎想要在其他地方被截断的字符串,souldn't修改源。
在这种情况下,可以更换:

  //尝试将线截断20个字符
行[20] ='\\ 0';//复制线到每个字符在一个时间
INT X;
为(X = 0; X&小于20; X ++)
{
    A [0] [X] =行[X];
}

  //行复制到每个字符在同一时间
INT X;
为(X = 0; X&小于20; X ++)
{
    A [0] [X] =行[X];
}
一个[0] [20] = 0;

I am reading from a file of which each line is longer than 63 characters and I want the characters to be truncated at 63. However, it fails to truncate the lines read from the file.

In this program we are assuming that the file has 10 lines only:

#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]);
    }


}

解决方案

You have this result because you forgot to add the null string terminator in the end of a[0].

There's several ways to do it. My favorite one is to leave line as is: since it seems you want the truncated string elsewhere, you souldn't modify the source. In that case, you can replace:

//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];
}

with

//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;

这篇关于我怎样才能完美地截断在C字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆