Home > Enterprise >  Find the shortest line from input (C)
Find the shortest line from input (C)

Time:10-31

I made a function that counts all characters of every line I get from input. Code below:

#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;
}

This works as intended, e.g. with the text file input.txt, which contains:

Password
longpassword
short
aaa
verylongpassword

and the following syntax for running the program:

./binary <input.txt

My program prints out:

8
12
5
3
16

Which is correct. My objective now is to print out the number of characters of the shortest line of the said file. Using the above example, I know that the shortest line has the character count of 3. My question is, how do I get this exact value? I thought about saving the value into another variable, and then check that variable against another callings of the function, which yielded the following code:

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;
}

Not only is the code pretty ugly and obfuscated, but it doesn't work correctly, too. Running the code on the same text file (input.txt with the content above) prints out:

Shortest line is --> 16

Which is obviously not correct.

CodePudding user response:

You are counting chars in the same line twice and always re-assign the shortestLine undconditionally:

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

Initialize a variable which holds your "winner" and use another variable to keep track of the length of the current line:

#include <limits.h>

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