首页 > 解决方案 > C:要求用户输入一个字符串。编写一个以字符串为参数的函数,如上所述加密消息并返回密文

问题描述

我目前正在处理一项任务,我以为我完成了它,但我的 while 循环处于一个恒定的无限循环中,我不知道我在哪里搞砸了。我试过寻求帮助,但助教帮助不大。如果您能看一看,将不胜感激。. . . . . . . . . . . . . . . .

#include <stdio.h>
#include <string.h>
#define Max_Length 100
#define Max_String 100

    char* encrypt_message (char* message, int length) //Encrypted Message function
    {
        char *cipher;
        char array_1 [(Max_Length + 1) / 2];
        char array_2 [(Max_Length + 1) / 2];
        int k = 0, i;
        int l = 0;
        for (i = 0; i < Max_Length; i++)
        {
            if (i % 2 == 1)
            {
                array_1[k] = message[i];
                k++;
            }
            else
            {
                array_2[l] = message[i];
                l++;
            }
        }
        cipher = strcat (array_1, array_2);
        cipher[Max_Length] = '\0';
        return cipher;
    }

    int main()
    {
        char plain_text[Max_String][Max_Length];
        char cipher_text[Max_String][Max_Length];
        int str_len, i, j;
        char *temp;
        char choice = 'N';
        int l = 0;
        do
        {
            char * str;
            printf("Please enter a message: ");
            gets(plain_text[l]);
            str_len = strlen(plain_text[l]);
            str = encrypt_message(plain_text[l], str_len);
            strcpy(cipher_text[l], str);
            printf("The encrypted message is: %s\n", cipher_text[l]);
            printf("Do you want to continue (Y/N)? : ");
            scanf("%c", &choice);
            l++;
        }
        while (choice == 'Y' || choice == 'y'); //Something is messing up (Constant While Loop)
        {
            printf("\n\n The original message in alphabetical order are\n");
            for (i = 0; i < l; i++)
            {
                for (j = 0; j < l - 1; j++)
                {
                    if (strcmp(plain_text[j], plain_text[j + 1]) > 0)
                    {
                        strcpy(temp, plain_text[j]);
                        strcpy(plain_text[j], plain_text[j + 1]);
                        strcpy(plain_text[j + 1], temp);
                    }
                }
            }
            for (i = 0; i < 1; i++)
            {
                printf("%s\n", plain_text[i]);
            }
        }
        return 0;
    }

标签: c

解决方案


如果你添加getcharafter scanf("%c", &choice);,你的问题将得到解决。

您遇到的问题是由输入流中留下换行符引起的。输入 ay并按下回车(并假设没有别的)后,输入流中会留下一个换行符;当gets在下一次迭代中被调用时,换行符被设置plain_text为“\n”。

当您输入多个字符时,可以观察到这一点:

$ ./main.exe
请输入留言:你好
加密的消息是:elhlo
您要继续(是/否)吗?: 是的,请
请输入信息: 加密信息为: spese lae
您要继续(是/否)吗?:

要解决上面观察到的问题,请添加另一个循环以消耗第一个之后的所有字符,直到找到换行符:

scanf("%c", &choice);
while(getchar() != '\n')
    continue;

现在观察结果:

$ gcc main.c -o main.exe; ./main.exe;
请输入留言:你好
加密的消息是:elhlo
您要继续(是/否)吗?: 是的,请
请输入留言:

笔记

gets不应该使用。改为使用fgets,因为它可以防止缓冲区溢出。


推荐阅读