【问题标题】:Find the shortest line from input (C)从输入中找到最短的线 (C)
【发布时间】: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。 (注意:shortestLineLengthshortestLine 更好,因为它的值是长度,而不是行。)
  • 在修复代码以记住最短行长度时,您需要考虑如何处理第一行。在这一点上,没有以前的最短线长度。有不同的处理方式,这是您应该考虑的。

标签: arrays c string


【解决方案1】:

您在同一行中计算了两次字符,并且总是无条件地重新分配 shortestLine

    while(fgets(inp,100,stdin)) {
        shortestLine = countAllChars(inp);
        if(shortestLine < countAllChars(inp)){
            shortestLine = countAllChars(inp);
        }
    }

初始化一个保存“获胜者”的变量,并使用另一个变量来跟踪当前行的长度:

#include <limits.h>

int shortestLine = INT_MAX;
int currentLineLength = INT_MAX;
while(fgets(inp,100,stdin)){
    currentLineLength = countAllChars(inp);
    if(currentLineLength < shortestLine) {
        shortestLine = currentLineLength;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多