首页 > 解决方案 > 如何让我的程序提示用户输入并使用函数将其存储到数组中?

问题描述

我需要使用一个函数来获取用户输入,将其存储到一个数组中以传递给另一个函数来解密或加密消息。

  int main()
{
    char inputBuf[SIZE];

    do
    {
        switch (getUserChoice())
        {
            case 1:
            getShift();
            break;

            case 2:
            getString(inputBuf[SIZE]);
            break;

        }
    } while(getUserChoice() != 4);

    return 0;
}

void getString(char inputBuf[SIZE])
{
    char inputBuf[SIZE];
    printf("Input: \n");
    fgets(inputBuf, SIZE, stdin)
}

标签: c

解决方案


对您的代码的一些改进...

数组作为指针传递。因此,将使用您的数组的函数声明为一个函数,该函数采用数组的指针和最大长度。

您仍然需要为getShiftand提供定义getUserChoice,并且可能为SIZE(ala #define SIZE 500)提供宏定义

void getString(char* inputBuf, size_t maxLength); // forward declare

int main()
{
    char inputBuf[SIZE];
    int choice;

    while((choice = getUserChoice()) != 4)
    {
        switch (choice)
        {
            case 1:
            {
                getShift();
                break;
            }

            case 2:
            {
                getString(inputBuf, SIZE);
                break;
            }
        }
    } 

    return 0;
}

void getString(char* inputBuf, size_t maxLength)
{
    printf("Input: \n");
    fgets(inputBuf, maxLength, stdin);
}

推荐阅读