Home > Blockchain >  Int parameter in argv[]
Int parameter in argv[]

Time:10-10

So basically I got this project to school where we need to pass int parameters into argv[]. The project is in C. We cannot use string.h

I tried to retype argv[] into int but since it is just a pointer it did not work.

Here is my code:

if(argv[1][0] == '1'){
            printf("Hodnota LEVEL je 1");

       } 
       else if(argv[1][0] == '2'){
           printf("Hodnota LEVEL je 2");

       }

As you can see I am currently checking if argv[] is equal to char '1' or '2' which is not what I want.

Only thing that comes to my mind is to replace '1' and '2' with some char variable and then recast it into int. After this process I can check if it is int 1 or int 2

Is there any other way to solve my problem?

CodePudding user response:

If you’re not allowed to use the standard library, then you can do something like this:

int val = 0;
for ( char *p = argv[1]; *p != 0; p   )
{
  val *= 10;
  val  = *p - '0’;
}

The character encodings for decimal digits are guaranteed to be sequential, so subtracting the encoding for '0' gives you the equivalent integer value - e.g., '1' - '0' == 1, '2' - '0' == 2, etc.

You may want to add some sort of validation - if argv[1] == "abcd", you’re going to get an interesting result.

If you are allowed to use the standard library, use strtol instead.

  • Related