【发布时间】:2021-12-15 04:34:57
【问题描述】:
我做了一个函数来计算我从输入中得到的每一行的所有字符。代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int countAllChars (char inp[])
{
int charCount = 0;
for(int i = 0; inp[i] != '\0'; i++) {
if(inp[i] == '\n' || inp[i] == EOF) {
continue;
} else {
charCount++;
}
}
return charCount;
}
int main ()
{
int total = 0;
char inp[1000];
while(fgets(inp,100,stdin)) {
printf("%d\n", countAllChars(inp));
}
return 0;
}
这按预期工作,例如使用文本文件 input.txt,其中包含:
Password
longpassword
short
aaa
verylongpassword
以及以下用于运行程序的语法:
./binary <input.txt
我的程序打印出来了:
8
12
5
3
16
这是正确的。我现在的目标是打印出上述文件最短行的字符数。使用上面的示例,我知道最短的行的字符数为 3。我的问题是,我如何得到这个确切的值?我考虑将值保存到另一个变量中,然后根据函数的另一个调用检查该变量,这产生了以下代码:
int countAllChars (char inp[])
{
int charCount = 0;
for(int i = 0; inp[i] != '\0'; i++) {
if(inp[i] == '\n' || inp[i] == EOF) {
continue;
} else {
charCount++;
}
}
return charCount;
}
int main ()
{
int total = 0;
int shortestLine = 0;
char inp[1000];
while(fgets(inp,100,stdin)) {
shortestLine = countAllChars(inp);
if(shortestLine < countAllChars(inp)) {
shortestLine = countAllChars(inp);
}
}
printf("Shortest line is --> %d\n", shortestLine);
return 0;
}
不仅代码非常丑陋和混淆,而且它也不能正常工作。在同一个文本文件(input.txt 与上面的内容)上运行代码会打印出:
Shortest line is --> 16
这显然是不正确的。
【问题讨论】:
-
只记录目前最小的,当你得到一个较小的线时更新
-
@klutt 这正是我的想法,我认为我的代码可以实现这一点。但事实并非如此。
-
countAllChars实现不正确。当它在inp缓冲区中看到'\n'字符时,它会执行continue。这将继续for循环,继续到i的下一个值。这是错误的,因为它在'\n'之后继续计算缓冲区中的字符。相反,您想从循环中break结束它。此外,测试EOF是错误的。EOF不是字符,fgets从不将其存储在缓冲区中。 -
您显示的记住最短行长的代码也有缺陷。在测试
inp当前是否是最短线之前,您有shortestLine = countAllChars(inp);。相反,使用int currentLineLength = countAllChars(inp);,然后确定currentLineLength是否是迄今为止看到的最短长度。如果是,则更新shortestLineLength。 (注意:shortestLineLength比shortestLine更好,因为它的值是长度,而不是行。) -
在修复代码以记住最短行长度时,您需要考虑如何处理第一行。在这一点上,没有以前的最短线长度。有不同的处理方式,这是您应该考虑的。