- #1
TheSourceCode
- 14
- 0
Here is the given assignment:
Write a code that would
parse the command line
and display the user’s first /
last name and (if given)
his/her age. The ‘-age’ key,
if present, could be the first
or, alternatively, the third
argument and indicates that
the following parameter is
age, as in the example
shown. If the command
line arguments are not
valid, an error message to
that effect should be
displayed. (You may use
string functions as needed.)
My program works as long as the user is inputting arguments with the -age key but crashes if any other time. Could I get a hint as to what is wrong?
Write a code that would
parse the command line
and display the user’s first /
last name and (if given)
his/her age. The ‘-age’ key,
if present, could be the first
or, alternatively, the third
argument and indicates that
the following parameter is
age, as in the example
shown. If the command
line arguments are not
valid, an error message to
that effect should be
displayed. (You may use
string functions as needed.)
My program works as long as the user is inputting arguments with the -age key but crashes if any other time. Could I get a hint as to what is wrong?
Code:
#include <stdio.h>
int main(int argc, char *argv[]){
if(argc < 3 || argc > 5 || argc == 4)
printf("Invalid command line arguements.\n");
if(!strcmp(argv[2], "-age") || !strcmp(argv[4], "-age"))
printf("Invalid command line arguements.\n");
if(argc == 3){
printf("Your first name is: %s\n", argv[1]);
printf("Your last name is: %s\n", argv[2]);
}
if(!strcmp(argv[1], "-age")){
printf("Your first name is: %s\n", argv[3]);
printf("Your last name is: %s\n", argv[4]);
printf("Your age is: %s\n", argv[2]);
}
if(!strcmp(argv[3], "-age")){
printf("Your first name is: %s\n", argv[1]);
printf("Your last name is: %s\n", argv[2]);
printf("Your age is: %s\n", argv[4]);
}
system("PAUSE");
return 0;
}