大家好,我正在阅读Kernighan和Ritchie撰写的C编程语言,并试图解决所有问题。该程序应该消除输入行末尾的所有空格和制表符,但不能正常工作。
我在我遇到问题的代码部分中添加了注释

#include <stdio.h>
#define MAXLINE 1000
int getline(char line[], int max);
void copy(char to[], char frm[]);
int main(void) {
    int maxLen=0;
    int currLen;
    char line[MAXLINE];
    char longestLine[MAXLINE];
    while((currLen=getline(line,MAXLINE)) > 0){
        if(currLen > maxLen){
            maxLen = currLen;
            copy(longestLine, line);
        }
    }
    if(maxLen>0){
        printf("%d\n", maxLen);
        printf("%s", longestLine);
    }
    return 0;
}
int getline(char line[], int max){
    int c,i;
    for(i=0;i<max-1 && (c=getchar())!=EOF && c!='\n';i++){
        line[i] = c;
    }
    if(c == '\n'){

        /* This is the logic i added to take care of the trailing
        spaces and tabs. Rest of the program is same as the book
        Its still counting spaces at the end of line when variable maxLen is
        printed in the main function, would like to know if the logic is
        erronous*/

        while(line[i] == ' ' || line[i] == '\t'){
            i--;
        }

        line[i]=c;
        ++i;
    }
    line[i] = '\0';
    return i;
}
void copy(char to[], char from[]){
    int i=0;
    while((to[i]=from[i])!='\0'){
        ++i;
    }
}

最佳答案

据我所知,您的程序正在返回输入的最长行,并且不会消除空格或制表符。

欢迎您通过以下链接查看解决方案:
solution to 1-18

希望这对您有所帮助
祝好运

08-19 18:44