Search code examples
catoi

Passing argument from main to function in C


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

    // Compile this program with:
    //      cc -std=c99 -Wall -Werror -pedantic -o rot rot.c


        #define ROT 3

        //  The rotate function returns the character ROT positions further along the
        //  alphabetic character sequence from c, or c if c is not lower-case

        char rotate(char c)

        {

                // Check if c is lower-case or not
                if (islower(c))
                {
                        // The ciphered character is ROT positions beyond c,
                        // allowing for wrap-around
                        return ('a' + (c - 'a' + ROT) % 26);

                }
                else
                {
                        return ('A' + (c - 'A' + ROT) % 26);;
                }
        }

        //  Execution of the whole program begins at the main function

        int main(int argc, char *argv[])
        {


                     for (int j = 2; j < argc; j++){
                        // Calculate the length of the second argument
                        int length = strlen(argv[j]);

                        // Loop for every character in the text
                        for (int i = 0; i< length; i++)
                        {
                                // Determine and print the ciphered character
                            printf("%c" ,rotate(argv[j][i]));
                            printf("%c" ,rotate(argv[j][i])-ROT);
                            printf("%d",i+1);
                            printf("\n");

                        }

                        // Print one final new-line character
                        printf("\n");
                    }
                        // Exit indicating success
                        exit(EXIT_SUCCESS);

                return 0;
        }

I am struggling with a program that rotates the given characters by the amount user type in as the first argument of argv.

Now I need to modify the program to achieve this. The question says I can use àtoi` function to do that.

My confusion is that How can my argv[1] value in Main be passed into function rotate (Variable ROT)?

The ideal output would be (using terminal in MAC)

./rot 1 ABC
AB1
BC2
CD3

Solution

  • ROT is a macro. You can't change it at runtime. Use a variable instead.

    (You need to error check strtol() and ensure there are as many argv[] passed before using them -- strtol() is better than atoi as helps detect errors).

     int rot = (int)strtol(argv[1], 0, 0);
    
    
     printf("%c" ,rotate(rot, argv[j][i]));
     printf("%c" ,rotate(rot, argv[j][i])-ROT);
    

    and change it to:

    char rotate(int rot, char c) {
     ...
    }
    

    and use rot instead of ROT.