我正在尝试 K&R 中的一个练习,它要求编写一个程序来读取一组文本行并打印最长的行。
我是按照这样的思路写的;
define a string of characters
write a function that marks the length of line until there's a newline
when encountered newline, the function again repeats
keep copying length to a variable if the length of newline is greater
copy the string (if of greater length) to another string
print the last copied string
我尝试编写函数 this mark the length 这肯定是错误的
int getlength(char str[],int lim)
{
int length ,c;
c = getchar();
while((c=getchar())!= '\n')
{
for (length=0; length < lim -1; length++)
c = str[length];
}
return length;
}
谁能建议我如何编写 getlength 函数。我不是要代码,而是要伪代码会很有帮助。
以下是我认为您在阅读帖子和评论时正在寻找的内容:
int getlength(char str[],int lim)
{
int length = 0;
int c;
while((c=getchar())!= '\n') //Get a character. If it's a newline, quit. Otherwise, keep going.
{
str[length] = c; //Add it to the string
length++; //Move to the next character
}
str[length] = '\0'; //Add the terminating null to the end of the string
return length;
}
此函数将在stdin上找到您给它的第一行的长度。
这就是您的原始功能不起作用的原因:
你有过:
int getlength(char str[],int lim)
{
int length ,c;
c = getchar();
while((c=getchar())!= '\n')
{
for (length=0; length < lim -1; length++)
c = str[length];
}
return length;
}
首先,您读取的字符c = getchar();
永远不会被处理,因为 while 语句在检查其条件时会覆盖它。请记住,while 循环将在每个循环开始时检查条件。我认为您想使用do {...} while(condition);
,但是如果您这样做,您会遇到错误,因为如果用户不输入任何内容,第一个 getchar() 调用将返回 '\n' 并且循环无论如何都会运行并将其添加到字符串中。
其次,内部循环遍历传递给它的字符串中的每个字符,并将其设置为最近读取的字符。我用 100 个字符的字符串尝试了你的代码并输入了“abcdef”。我得到了 99 个 f - 它遍历“abcdef”中的每个字符并将整个字符串设置为当前字符,并且由于 'f' 是最后一个字符,所以它被放在最后。
第三,您没有在字符串末尾添加终止 null。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句