Reputation: 71
I'm having trouble with comparing strings in C. Firstly, I need to find the length of each string from command-line arguments, and then compare them as well as printing the biggest one.
So far, it's just printing the length of each typed string. I need to compare them according to length, not alphabetic order.
I don't understand why is it now working and what I should do fix it? Thank you!
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
int i, length;
for(i = 0; i<argc; i++)
{
length = strlen(argv[i]);
printf("%s %d\n", argv[i], length);
if(strlen(argv[i]) < strlen(argv[i+1]))
{
printf("%s is the biggest \n", argv[i+1]);
}
else
{
printf("%s is the biggest \n", argv[i]);
}
}
return 0;
}
Upvotes: 3
Views: 10755
Reputation: 4599
This will not segfault ...
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
int i, length;
for(i = 0; i<argc - 1; i++)
{
length = strlen(argv[i]);
printf("%s %d\n", argv[i], length);
if(strlen(argv[i]) < strlen(argv[i+1]))
{
printf("%s is the biggest \n", argv[i+1]);
}
else
{
printf("%s is the biggest \n", argv[i]);
}
}
return 0;
}
Upvotes: 0
Reputation: 33430
There are a few problems with your code.
First of all, argv[i+1]
is an illegal operation if you're doing i < argc
in the for
. You need to change i < argc
to i < argc - 1
in the for
.
Secondly, you are probably not comparing the strings you want. argv[0]
is the string representing the path of your program; the first argument passed to your program is argv[1]
. Therefore, you need to change the i = 0
in the for
to i = 1
.
Finally, if you only want the biggest string, you should not do any printing in the for
loop. Rather, you should create two variables like max_length
and max_length_idx
where you would store the length and index of the largest string found so far. Then, after the for
loop, your program would print out the string argv[max_length_idx]
.
Upvotes: 8
Reputation: 9216
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
int i, max_length, max_index;
max_index = 0;
max_length = strlen(argv[0]);
for(i = 1; i < argc; i++)
{
if(strlen(argv[i]) > max_length)
{
max_length = strlen(argv[i]);
max_index = i;
}
}
printf("The longest is: %s with length equal: %d\n", argv[max_index], max_length);
return 0;
}
Upvotes: 4