0

Is it possible to use the main function to define what an input can be?

int main(int argc, string argv[])

For example, within the argv[], the number of arguments can be defined to 1, 2, 3, etc. Can they also be defined as +/-, < /=/ >, etc to be effective as limits to the command-line input from the user?

6
  • so you're asking whether symbols can be passed as command-line arguments?
    – kzidane
    Jul 23, 2015 at 17:29
  • I needed to convert the strings to ints first but I was also looking for... check to see if that specific character was used in the input such as, did the user input a - sign or an =. Is it easiest to use the ascii values? Jul 24, 2015 at 5:19
  • I needed to convert the strings to ints first but I was also looking for... check to see if that specific character was used in the input such as, did the user input a - sign, as opposed to using is the number < 0, then using that to return 0. Is it easiest to use the ascii values if I'm looking for the specific symbols? Jul 24, 2015 at 5:25
  • Can you show a concret example of what you want to try? This way it would be easier to give you a more detailed answer.
    – wallek876
    Jul 24, 2015 at 5:40
  • So maybe.... in the main function int main(int argc, string argv[]) ... if (argv[x]["-"]) or it might be more common to for someone to type a dollar sign when you don't want them to so maybe... if (argv[x]["$"]) to say, "if the first position in argv is a dollar sign"... Jul 24, 2015 at 7:15

1 Answer 1

1

Sure, it is possible. But you will have to check if the arguments given to main are valid for your program, and also you will have to convert the arguments to the type you need, since the arguments are strings.

Example:

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

int main(int argc, char* argv[])
{
    if (argc == 1)
    {
        printf("Enter your name: ");
        string name = GetString();

        printf("Thanks, %s %d", name, argc);
    }
    else if (argc == 2)
    {
        if (argv[1][0] == 'a' && strlen(argv[1]) == 1)
        {
            printf("The argument is the letter a \n");
        }
        else if(argv[1][0] == 'b' && strlen(argv[1]) == 1)
        {
            printf("The argument is the letter b\n");
        }
        else
        {
            printf("Invalid argument\n");
        }
    }
    else
    {
        printf("Invalid number or arguments\n");
    }

    return 0;
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .