#include <stdio.h>
int main()
{
char s[20]={0};
int i;
gets(s);
while(s[i] != '\0'){
if( ( s[i]>='a' && s[i]<='v') || (s[i]>='A' && s[i]<='V'))
s[i] += 4;
else if ( s[i]>'v' && s[i]<='z' )
s[i] = 'a' + s[i] - 'w';
else if(s[i]>='V' && s[i]<='Z')
s[i] = 'A' + s[i] - 'W';
else{printf("error\n");return 0;}
i++;
}
printf("%s\n",s);
return 0;
}
这个根据ascii码的性质,给每个字母+4就行。遇到最后的Z 返回重置。
#include<iostream>
using namespace std;
int main()
{
char a[5]={'C','h','i','n','a'};
for(int i=0;i<5;i++)
{
a[i]+=4;
cout<<a[i];
}
}
遍历字符串,对每个字符+4然后输出。
你题目的解答代码如下:(如有帮助,望采纳!谢谢! 点击我这个回答右上方的【采纳】按钮)
#include<stdio.h>
int main()
{
char s[21], ch;
int i,f=1;
for (i = 0; i<20 && (ch=getchar()) != '\n'; i++) {
if (ch >= 'A' && ch <= 'Z') {
s[i] = (ch-'A'+4)%26 + 'A';
} else if (ch >= 'a' && ch <= 'z') {
s[i] = (ch-'z'+4)%26 + 'z';
} else {
f=0;
break;
}
}
s[i] = '\0';
if (i==0 || f==0)
printf("error");
else
printf("%s",s);
return 0;
}
供参考:
#include<iostream>
using namespace std;
int main()
{
int i = 0;
char a[21] = { 0 };
while ((a[i] = cin.get()) != '\n')
{
if (a[i] >= 'a' && a[i] <= 'z')
a[i] = (a[i] - 'a' + 4) % 26 + 'a';
else if (a[i] >= 'A' && a[i] <= 'Z')
a[i] = (a[i] - 'A' + 4) % 26 + 'A';
else {
i = 0;
break;
}
i++;
if (i == 20) break;
}
a[i] = '\0';
if (i == 0)
cout<<"error"<<endl;
else
cout<< a<<endl;
return 0;
}