简体   繁体   English

无法输出最长的字符串

[英]Unable to output the longest string

Problem Statement: write a program that reads a set of text lines and prints the longest.问题陈述:编写一个程序,读取一组文本行并打印最长的文本行。

Program:程序:

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

Expected Output:预期输出:

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

Actual Output:实际输出:

hello
world!!
The longest lenght is 7
�

Somehow, I am able to print the correct longest lenght but not the string itself.不知何故,我能够打印正确的最长长度,但不能打印字符串本身。 I thought I miss the null byte, but it's there and the error still persist.我以为我错过了空字节,但它在那里并且错误仍然存​​在。

As @chux pointed out, i made a silly mistake by using equal sign ("==") instead of assignment sign ("=") on line #34:正如@chux 指出的那样,我在第 34 行使用等号(“==”)而不是赋值符号(“=”)犯了一个愚蠢的错误:

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

So the corrected program would be所以修正后的程序将是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM