I want to make a program, which prints the number of smallest length of string. I have a file of words, which I open from stdin and save it to buffer.
My code so far prints the length of each word. But I can't figure out how to compare these numbers.
For example in file are:
Hello
Hi
My program does:
6
3
The output should be:
3
I can't figure ou how to continue. Do you have any advice?
#include <stdio.h>
int min_stat(char str[])
{
int min=0;
for(int i=0; str[i] != '\0'; i )
{
min ;
}
return min;
}
int main(int argc, char *argv[])
{
if(argc < 1){
fprintf(stderr,"Error\n");
return 1;
}
char param = argv[1][0];
int val=100;
char buffer[val];
if(param == '1')
{
while(fgets(buffer, val, stdin) != NULL)
{
int a = min_stat(buffer);
printf("%d\n", a);
}
}
return 0;
}
CodePudding user response:
You need to save the minimum lenght of the string somewhere and update it if a shorter string is detected. Your min_stat
function returns the number of characters of the string.
I would use something like this:
#define MAX_LENGHT 1000
int main(int argc, char *argv[])
{
if(argc < 1){
fprintf(stderr,"Error\n");
return 1;
}
char param = argv[1][0];
int val=100;
char buffer[val];
/* the maximum possible lenght */
int min_lenght = MAX_LENGHT;
if(param == '1')
{
while(fgets(buffer, val, stdin) != NULL)
{
int a = min_stat(buffer);
/* update the mimimum lenght if it is smaller
than the current value */
if (a < min_lenght) {
min_lenght = a;
}
printf("%d\n", a);
}
}
/* print the minimum lenght */
printf("Minimum: %d\n", min_lenght);
return 0;
}
You should not use a variable to initialize the char array, because you are using Variable Lenght Arrays (VLA) and not static arrays. If you are learning c you should use static arrays and so:
char buffer[MAX_LENGHT];
where MAX_LENGHT
is a constant or a pre-processor definition.