gpt4 book ai didi

程序中找不到打印最长输入行的bug

转载 作者:太空宇宙 更新时间:2023-11-04 04:37:18 25 4
gpt4 key购买 nike

#include <stdio.h>
#include <stdlib.h>

#define MAXLINE 1000

int mygetline( char line[], int maxline); /*will return length */
void copy (char to[], char from[]);

int main(){

int len; // length of the line
int max; // maximum length seen so far
char line[MAXLINE];
char longest[MAXLINE];

max = 0;
while((len = mygetline(line, MAXLINE)) >0){
if (len>max){
max = len;
copy(longest, line);
}

if (max>0){
printf("%s", longest);
}
}
return 0;
}

/*getline: reads a line into s, and returns length of the line */
int mygetline(char s[], int limit){

int c, i;
for(i=0; i<limit-1 && (c=getchar())!= EOF && c!= '\n'; ++i){
s[i] = c;
}

if (c=='\n'){
s[i] = c;
++i;
}

s[i] = '\0';
return i;
}

/*copy: copy 'from' into 'to'; assume to is big enough */
void copy (char to[], char from[]){

int i=0;
while((to[i] = from[i] != '\0')){
++i;
}
}

以上是我打印最长输入行的代码。代码编译没有任何错误,但是当我运行程序时它没有打印任何东西。我找不到这里出了什么问题。

最佳答案

这有点简单,它通过使用可用的字符串函数来完成这项工作,而不是逐个检查一个字符。如果需要,您可以打开一个文件进行输入并替换 stdin

#include <stdio.h>
#include <string.h>

#define MAXLINE 1000

int main(){
int len; // length of the line
int max; // maximum length seen so far
char line[MAXLINE];
char longest[MAXLINE];
char *sptr;
max = 0;
while((sptr = fgets(line, MAXLINE, stdin)) != NULL) {
if ((sptr = strtok(sptr, "\r\n")) != NULL) {
len = strlen(sptr);
if (len > max) {
max = len;
strcpy(longest, sptr);
}
}
}
if (max)
printf("%d: %s\n", max, longest);
else
printf("No strings read\n");
return 0;
}

关于程序中找不到打印最长输入行的bug,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29633174/

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