荼蘼== 发表于 2022-5-23 18:01:37

求助用数组和字符串解决凯撒加密

基于字符串实现整串文字的“凯撒加密”

1)定义字符数组 char input 保存输入的文字

2)使用gets获取输入的整串文字,并保存在 input 数组

3)基于字符指针遍历数组,循环执行凯撒加密

4)输出字符仍然保存在 input 数组

5)整行打印转意后的字符

例如:

input pos num(-5<pos<5): 3

input string: Hello the world!

output string:Khoor wkh zruog!

要求使用字符指针遍历
谢谢各位大佬啦!

傻眼貓咪 发表于 2022-5-23 18:26:02

#include <stdio.h>
#include <string.h>
#define N 20

void encryption(char* str, size_t n) {
    for (char* p = str; p < str + n; ++p) {
      if (((*p) >= 'a' && (*p) <= 'w') || ((*p) >= 'A' && (*p) <= 'W')) {
            (*p) += 3;
      }
      else if (((*p) >= 'x' && (*p) <= 'z') || ((*p) >= 'X' && (*p) <= 'Z')) {
            (*p) -= 23;
      }
    }
}

int main(void) {
    char input;
    gets(input);
    encryption((char*)input, strlen(input));
    printf("%s", input);
    return 0;
}

豆嘉木 发表于 2022-5-23 19:15:49

#include <stdio.h>
#include <string.h>
#define N 20

void encryption(char* str, size_t n) {
    for (char* p = str; p < str + n; ++p) {
      if (((*p) >= 'a' && (*p) <= 'w') || ((*p) >= 'A' && (*p) <= 'W')) {
            (*p) += 3;
      }
      else if (((*p) >= 'x' && (*p) <= 'z') || ((*p) >= 'X' && (*p) <= 'Z')) {
            (*p) -= 23;
      }
    }
}

int main(void) {
    char input;
    gets(input);
    encryption((char*)input, strlen(input));
    printf("%s", input);
    return 0;
}

jhq999 发表于 2022-5-23 20:45:27

本帖最后由 jhq999 于 2022-5-23 21:41 编辑

借花献佛,装个B{:5_109:}
void encryption(char* str, size_t n) {
    for (char* p = str; *p; ++p) {
               
      if (((*p) >= 'a' && (*p) <= 'z') || ((*p) >= 'A' && (*p) <= 'Z')) {
                *p+=n;
                if (((*p) < 'a' || (*p) > 'z') && ((*p) < 'A' || (*p) > 'Z'))
                        if(n<0)*p+=26;
                        else
                                *p-=26;
                       
      }
      
    }
}
/*
input pos num(-5<pos<5): 3

input string: Hello the world!

output string:Khoor wkh zruog!
*/
int main(void)
{
        int m=0;
        printf("input pos num(-5<pos<5):");
        scanf("%d",&m);
        fflush(stdin);
        printf("\ninput string:");
        //char ch=getchar();
        ungetc(getchar(),stdin);
        //n=stdin->_cnt;
        char* input=(char*)malloc(stdin->_cnt);
        gets(input);
        encryption((char*)input,m);
        printf("output string:%s", input);
        free(input);
        return 0;
}
页: [1]
查看完整版本: 求助用数组和字符串解决凯撒加密