c - 如何在 'a' 和 'z' 之间移动几个字母

标签 c

我有一个练习,我需要取一个字符串,反转它,然后输入一个数字,每个字母需要根据该数字移动几个字母,我需要在所有这些中使用与指针。 这是我的代码:

#include <stdio.h>

#define LEN 100
void decryptText(char* encText, int n);
int main(void)
{
    char str[LEN] = { 0 }; 
    int num = 0; 
    printf("Please enter a string :\n");
    fgets(str, LEN, stdin);
    printf("\nPlease enter a number:\n");
    scanf("%d", &num);
    decryptText(str, num);
    getchar();
    system("PAUSE");
    return 0;
}

void decryptText(char* encText, int n)
{
    int i = 0, len = 0 , value = 0 ;
    char moved = ""; 

    for (i = 0; i<LEN; i++){
        if (*encText == '\0') 
        {
            break;
        }
        encText++;
    }
    len = i;
    encText--;
    printf("The secret message is: \n\n");
    for (i = len; i>0; i--)
    { 
        value = (int*)(encText--); 
        moved = (char)(value + n);
        *encText = moved; 
        printf("%c", *encText);
    }
    printf("\n\n");
}

该程序无法运行,我仍然需要仅在“a”和“z”之间输入字母,并且无法更改指针来移动字母。

最佳答案

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define LEN 100

void decryptText(char* encText, int n);

int main(void){
    char str[LEN] = { 0 }; 
    int num = 0; 
    printf("Please enter a string :\n");
    fgets(str, sizeof(str), stdin);
    str[strcspn(str, "\n")] = '\0';//remove newline
    printf("\nPlease enter a number:\n");
    scanf("%d", &num);
    num = num % 26;
    decryptText(str, num);
    //getchar();
    system("PAUSE");
    return 0;
}

void decryptText(char* encText, int n){
    int i = 0, len = 0 , value = 0 ;
    unsigned moved = '\0';

    for (i = 0; *encText; i++){
        ++encText;
    }
    len = i;
    --encText;

    printf("The secret message is: \n\n");
    for (i = len; i>0; i--){
        value = *encText;
        if(isupper(value))
            value = tolower(value);
        if(islower(value)){
            moved = value + n;
            if(moved > 'z')
                moved = 'a' -1 + moved - 'z';
            else if(moved < 'a')
                moved = 'z' +1 + moved - 'a';
            *encText = moved;
        }
        printf("%c", *encText--);
    }
    printf("\n\n");
}

关于c - 如何在 'a' 和 'z' 之间移动几个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36533789/

相关文章:

c - 检查 if (char == '\n' ) 时出现段错误

c - 读取和添加从 C 文件中读取的整数

无法打破 c 循环

c - Freetype 无法使用 MinGW 在 Windows 上编译

c - '%' 和格式说明符之间的数字在 scanf 中意味着什么?

c - Hangman 程序帮助(C 编程简介)

c - 缺少 kernel32.dll 的依赖项

c - 使用C、winsock(windows)在三星Tizen推送服务器中推送消息

c - 细粒度多线程——一个工作任务应该做多少事情?

c - 使用 sscanf 从行读取,包括空格,中断其他字符