原题链接:信息加密
解题思路:
他这个信息加密操作主要是对大小写字母往后移一位,如果是最后一个字母,则加密成第一位。
可能出现的问题:
输出:Ifmmp! 使用cin读入字符串,因为cin不能读取空格,所以当遇到空格默认为读取结束。
解决方法:cin>>s; 替换为 getline(cin,s);这样就能接受字符串中的空格。
普通方法:
#include<iostream>
#include<cstring>
using namespace std;
int main(){
string s;
getline(cin,s);
for(int i=0;i<s.size();i++){
if((s[i]>='a' && s[i]<='z')||(s[i]>='A' && s[i]<='Z')){
if(s[i]=='z' || s[i]=='Z') s[i]=(char)(s[i]-25);
else s[i]=(char)(s[i]+1);
}
}
cout<<s;
return 0;
}
公式法:
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
getline(cin, s);
for (auto &c : s)
if (c >= 'a' && c <= 'z') c = (c - 'a' + 1) % 26 + 'a';
else if (c >= 'A' && c <= 'Z') c = (c - 'A' + 1) % 26 + 'A';
cout << s << endl;
return 0;
}
自动算空格法:
#include<bits/stc++.h>
using namespace std;
int mian(){
char ch;
while(scanf("%c",&ch)==1){
if(ch>='a'&&ch<='z')
ch=(ch+1-'a')%26+'a';
else if(ch>='A'&&ch<='Z')
ch=(ch+1-'A')%26+'A';
cout<<ch;
}
}
PS:(涉及的一些知识点)
for(auto a:b)的两种用法
for(auto a:b)中b为一个容器,效果是利用a遍历并获得b容器中的每一个值,但是a无法影响到b容器中的元素。
for(auto &a:b)中加了引用符号,可以对容器中的内容进行赋值,即可通过对a赋值来做到容器b的内容填充。
万能头文件,但在有些比赛中规定不能使用,编译时间长,部分编译器不支持
#include<bits/stc++.h>