gpt4 book ai didi

C 编程语言练习 1-18

转载 作者:行者123 更新时间:2023-11-30 19:29:40 25 4
gpt4 key购买 nike

大家好,我正在阅读 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

我希望这有帮助祝你好运

关于C 编程语言练习 1-18,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52493001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com