Search code examples
cstringargc

Read a specific letter using argv then using that for a switch (C Program)


This is for Homework

This is kind of a duplicate from one of my posts, but I'm having issues with command line reading. I have to alphabetize the planets and that's a simple task, however getting my program to read the command line argument then using that for my switch is the issue. I'll post my program and go further into detail after that.


#include<stdio.h>
#include<string.h>

void alpha(char planet[][9], char tempo[9]){
    int i, j;

     for(i=0;i<=9;i++)
      for(j=i+1;j<=9;j++){
         if(strcmp(planet[i],planet[j])>0){
            strcpy(tempo,planet[i]);
            strcpy(planet[i],planet[j]);
            strcpy(planet[j],tempo);
         }
      }
}
int main(int argc , char *argv[]){

   char str[][9] = {"Earth", "Jupiter", "Mars", "Mercury", "Neptune", "Pluto", "Saturn", "Uranus", "Venus"};
   char temp[9];

    if (argc == 3) {
    switch (argv[1][1]) { 


    case 'a':
    alpha(str, temp);
    printf("The planets in alphabetical order are:  ");
   for(int i=0;i<=9;i++)
      printf("%s, " , str[i]);
    printf("\n");

   return 0;
}
}
}

So for my program to go ahead and alphabetize the planets I need to type in the command -o a after running the program.

So it'd be like this:

./planets -o a

From my understanding the if (argc == 3) line of code reads the position of the character entered. That would skip the -o and only care about the a in the command line. However this doesn't work and I have no clue why. Also when I compile the program it has a comma before Earth and Venus.

So it complies like this(without using the command line portion):

,Earth, ......Venus,

How would I get rid of the comma before Earth and after Venus?

Any help would be appreciated!


Solution

  •  ./planets    -o       a
     argv[0]   argv[1]   argv[2]
    

    Now earlier you were checking o by passing argv[1][1]. That's why switch was failing.

    Also you had undefined behaviour accessing array index out of bound.

    That's why the change

    for(i=0;i<9;i++)
    

    Because the array has 9 elements. Also in the second loop for(j=i+1;j<9;j++)