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