Reputation: 69
so I have the following program which outputs the parameter with the maximum length. I want to make an exception so when I give it 0 parameters I get an error telling me that I need at lest one parameter.
// Program which given an number of program parameters
// (command-line parameters, calulates the length of each one
// and writes the longest to standard output.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
int i;
int maxLength = strlen(argv[1]);
char* maxString = argv[1];
if (argc<=0)
{
printf("You cannot have 0 parameters\n");
exit(0);
}
for(i = 2; i < argc; ++i)
{
// find out the length of the current argument
int length = strlen(argv[i]);
if (maxLength < length)
{
maxLength = length;
maxString = argv[i];
} // if
} // for
printf("Largest string is %s\n", maxString);
} // main
This is my code but for some reason I am getting a segmentation error when I'm giving it 0 arguments, instead of the message.
Any thoughts?
Upvotes: 0
Views: 2050
Reputation: 279
If you give zero arguments in command line argc
will be 1 not 0. The executable's name will be the first argument.
Upvotes: 3
Reputation: 392911
Edit after editing the question: Also you're using argv[1]
before you checked argc
. This is an error.
If you pass no arguments, argc
is going to be 1
(because argv[0]
is usually the executable name).
So
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
if(argc<=1)
{
printf("You cannot have 0 parameters\n");
exit(255);
} else
{
int i;
int maxLength = 0;
const char* maxString = 0;
for(i = 1; i < argc; ++i)
{
// find out the length of the current argument
int length = strlen(argv[i]);
if(maxLength <= length)
{
maxLength = length;
maxString = argv[i];
}
}
printf("Largest string is %s\n", maxString);
}
} // main
Upvotes: 4