【问题标题】:Program adds random characters to string in C程序在C中向字符串添加随机字符
【发布时间】:2020-02-01 14:42:22
【问题描述】:

我正在学习 C,我偶然发现了一个错误,我似乎无法理解它。

此代码应该接受多行文本(后跟 Enter),将各行相互比较,在遇到 EOF(又名 crtl - Z)时停止比较,选择最长的字符串并将其打印到控制台。

它会这样做,但是在打印出文本时,它有时会在输出中添加一些额外的字符。

这是代码:

int get_line(char s[]);
void copy(char from[], char to[]);

main()
{
    int len;
    char line[1000];                       //the array which is used to compare
    char longest[1000];                    //the array in which the longest line will be stored
    int max = 1;                           //the maximum length of a line
    while ((len = get_line(line)) > 0)     //checks if the length of a line in more than 0
        if (len > max)
        {
            max = len;
            copy(line, longest);
        }
    if (max > 0)
        printf("%s", longest);             //prints out the longest line, if it exists
}

int get_line(char s[])
{
    int  c, i;
    for (i = 0; (c = getchar()) != EOF && c != '\n'; ++i)     //reads the line until ^Z of Enter
        s[i] = c;
    return (i);
}

copy(char from[], char to[])
{
    for (int i = 0; from[i] != '\n'; ++i)
        to[i] = from [i];
}

【问题讨论】:

  • 如果没有阅读您的代码,这几乎总是意味着您无法在某处对字符串进行空终止。
  • 您希望'\n' 在您的代码中的哪个位置输入数组?
  • 是的,看看get_line()
  • 就我对C的理解,我认为'\n'是在getchar()函数中按Enter键进入的。
  • 您在copy 中遇到了类似的问题:它应该在达到终止空值时停止,并确保空值终止副本。 (或者重写以使用标准strcpy()。)我还必须指出您的代码存在安全漏洞:如果一行超过1000 个字符,它将溢出您的缓冲区。我理解在开始时希望保持简单,但避免养成坏习惯也很重要。

标签: arrays string getchar


【解决方案1】:

在 C 中,字符串是一个以\0 结尾的字符数组,这称为null terminated String。 所以当调用printf("%s",longest)时,它会打印出longest[]数组中长度为1000的每个元素。

要解决此问题,您必须将 char 数组的长度设置为实际字符串的长度加 1,并设置 longest[length +1] = '\0'

这将告诉printf() 函数字符串以长度 + 1 结束。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 2019-08-07
    • 1970-01-01
    相关资源
    最近更新 更多