Parsing command line arguments in C

  • Thread starter Thread starter TheSourceCode
  • Start date Start date
  • Tags Tags
    Line
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
5 replies · 3K views
TheSourceCode
Messages
14
Reaction score
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?

Code:
#include <stdio.h>
int main(int argc, char *argv[]){ 
  if(argc < 3 || argc > 5 || argc == 4)
    printf("Invalid command line arguments.\n");
  if(!strcmp(argv[2], "-age") || !strcmp(argv[4], "-age"))
    printf("Invalid command line arguments.\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;
}
 
Physics news on Phys.org
Can you provide an example valid arguments? It said the age argument could be first or third, but in your program, it looks like it's the third or fifth...so I'm a little lost.
 
"if(argc < 3 || argc > 5 || argc == 4)"

You said age if given, so that means age input is not necessarily expected right?
 
Sorry, let me clarify a little. Valid input would look something like this:

Code:
program.exe John Doe -age 43
or
Code:
program.exe -age 56 Jane Doe
or
Code:
program.exe Bob Smith
Where program.exe is argument 0 and so on...
 
If the age is not suppled, your program would attempt to read or write past the end of the argv array. Read your source code and attempt to find out where.

This is something that is very important to avoid. Every time you access an array element that might not exist, check the array size (or bounds) first!
 
Thanks for the feedback everyone, I got it to work! I really should have noticed the issue before.