无法输出最长的字符串

时间:2016-09-22 03:50:10

标签: c

问题陈述:编写一个程序,读取一组文本行并打印最长的文本。

程序:

#include <stdio.h>
#define MAX 100

int getlinetext(char s[]);

int main(void)
{
    char longest[MAX];
    int longestlenght = 0;
    char line[MAX];
    int lenght;

    while ((lenght = getlinetext(line)) > 0){
        if(lenght > longestlenght){
            longestlenght = lenght;
            int i = 0;
            while (line[i] != '\0'){
                longest[i] = line[i];
                i++;
            }
            longest[i] = '\0';
        }
    }
    printf("The longest lenght is %d\n", longestlenght);
    printf("%s\n", longest); 
    return 0;
}

int getlinetext(char line[])
{
    int i=0;
    int c;
    while ((c = getchar()) != EOF){
        line[i] == c;
        if (c == '\n')
            break;
        i++;
    }
    line[i] = '\0';
    return i;
}

预期产出:

hello
world!!
The longest lenght is 7
world!!

实际输出:

hello
world!!
The longest lenght is 7
�

不知何故,我能够打印正确的最长长度而不是字符串本身。我以为我错过了空字节,但它就在那里,错误仍然存​​在。

1 个答案:

答案 0 :(得分:1)

正如@chux指出的那样,我在第34行使用等号(“==”)代替分配符号(“=”)犯了一个愚蠢的错误:

line[i] == c -> line[i] = c 

所以纠正的程序将是

#include <stdio.h>
#define MAX 100

int getlinetext(char s[]);

int main(void)
{
    char longest[MAX];
    int longestlenght = 0;
    char line[MAX];
    int lenght;

    while ((lenght = getlinetext(line)) > 0){
        if(lenght > longestlenght){
            longestlenght = lenght;
            int i = 0;
            while (line[i] != '\0'){
                longest[i] = line[i];
                i++;
            }
            longest[i] = '\0';
        }
    }
    printf("The longest lenght is %d\n", longestlenght);
    printf("%s\n", longest); 
    return 0;
}

int getlinetext(char line[])
{
    int i=0;
    int c;
    while ((c = getchar()) != EOF){
        line[i] = c;
        if (c == '\n')
            break;
        i++;
    }
    line[i] = '\0';
    return i;
}