将参数从main传递给C中的函数

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;
        }

我正在努力使用一个程序,该程序将给定的字符按用户输入的数量作为 argv 的第一个参数进行旋转。

现在我需要修改程序来实现这个。问题说我可以使用 àtoi` 函数来做到这一点。

我的困惑是如何将 Main 中的 argv[1] 值传递给函数旋转(变量 ROT)?

理想的输出是(在 MAC 中使用终端)

./rot 1 ABC
AB1
BC2
CD3

ROT 是一个宏。您无法在运行时更改它。请改用变量。

(您需要进行错误检查 strtol() 并确保在使用它们之前传递了尽可能多的 argv[] -- strtol() 比 atoi 更好,因为它有助于检测错误)。

 int rot = (int)strtol(argv[1], 0, 0);


 printf("%c" ,rotate(rot, argv[j][i]));
 printf("%c" ,rotate(rot, argv[j][i])-ROT);

并将其更改为:

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

并使用 rot 而不是 ROT