-2

here is a program which printing some information about my self in this program if the user scanning /n its printing the name and etc. but when i'm running this program using gcc its printing nothing at all. i need to scan the parameters using argv and argc. how can i solve that?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 10

int main(int argc, char** argv)
{
    for (int i = 1; i < SIZE; i++)
    {
        if (argv[i] == ' ')
        {
            break;
        }
        if (argv[i] == 'n' || argv[i] == 'b' || argv[i] == 'f' || argv[i] == '?' && argv[i - 1] == '/')
        {
            switch (i)
            {

            case 'n':
                printf("my name is : Daniel Zingerman \n");
                break;
            case 'b':
                printf("my birth date is: 2/11 \n");
                break;
            case 'f':
                printf("my favorite food is: ice cream \n");
                break;
            case '?':
                printf("the instruction of the program:");
                printf("There is a lot of parameters you can scan into the program:");
                printf("1. /n - printing the name");
                printf("2. /b - printing the birth date");
                printf("3. /n - printing the favorite food");
                printf("4. /? - printing the instructions");

                break;
            }
        }


    }
    system("pause");
    return(0);
}

2 Answers2

0

You should use argc value to know what is last argument. Or you should test argv[i] == NULL. You seem not to understand argv is char **, so argv[i] is a char *, not a char.

Also learn to use getopt(), or getopt_long().

jdarthenay
  • 3,062
  • 1
  • 15
  • 20
0

The argv[] array is created from the program name in argv[0] and then the command line arguments separated by spaces
/n /b /f will be returned in argv[1], argv[2] & argv[3], not as a single 'string' in argv[1]

Use argc to limit how many elements of argv[] you test, so that you do not go out of bounds:
for (int i = 1; i < argc; i++) {

Now you need to check that you have valid command line arguments:
if ((strcmp(argv[i], "/n") == 0) || ...

As you need an integer value for the case tests, use the second element of the argv[i]:
switch (argv[i][1]) {

anita2R
  • 192
  • 1
  • 8