需要帮助将我的主要功能代码转换为单独的功能

我的账户

对于学校作业,我将在 main() 中创建变量,该变量将存储计数并将指向这些变量的指针传递给您的函数,以便函数可以通过指针修改变量。这是一项学校作业,所以与其有人给我答案,我更希望有人可以帮助我指出使用指针的正确方向。该准则确实有效,但还不是我想要的方式。

代码如下

void myFunction(int *letters, int *numbers, int *otherCharacters){
}



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

// Code for command line argument
    if (argc == 2) {
      int letters = 0;
      int numbers = 0;
      int otherCharacters = 0;
      int totalCharacters;
      int length = strlen(argv[1]);

      for (int i = 0; i < length; ++i){
        if (isalpha(argv[1][i]) != 0)
          ++letters;
        if (isdigit(argv[1][i]) != 0)
          ++numbers;
        if (isdigit(argv[1][i]) == 0 && isalpha(argv[1][i]) == 0)
          ++otherCharacters;
      }
      totalCharacters = letters + numbers + otherCharacters;
      
      printf("%i letters\n%i digits \n%i other characters\n%i characters total\n", letters, numbers, otherCharacters, totalCharacters);
      
    }

我希望letters, numbers, otherCharacters, and totalCharacters在 myFunction() 中使用指针而不是更改主函数中的值。任何有关如何使用指针的帮助将不胜感激。同样,我不是在寻求答案,因为我想自己完成这项任务。

重的

似乎该函数应该查看一个字符串并告诉您有多少个字母、数字和其他字符。它需要将计数作为指针和字符串。

void countCharacters(const char *string, int *letters, int *numbers, int *other) {
    ....
}

因为它们是指针,所以在递增它们时,您需要首先取消引用它们以获取它们的值。取而代之的letters++(*letters)++.

我们可以替换主代码以显示您如何调用它。

int main(int argc, char * argv[]) {
    // Exit early to avoid deeply nesting all the code.
    if (argc != 2) {
        perror("please supply a string");
        return 1;
    }

    int letters = 0;
    int numbers = 0;
    int other = 0;

    // Pass in the string (already a pointer) and the counts as pointers.
    countCharacters(argv[1], &letters, &numbers, &other);
    int total = letters + numbers + other;
      
    printf("%i letters\n%i digits \n%i other characters\n%i characters total\n", letters, numbers, other, total);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章