![](/img/trans.png)
[英]Caesar Cipher in C++: How to convert a message to integers without too many if statements?
[英]how to convert message to cipher message?
#include <iostream>
using namespace std;
int main()
{
string message;
cout << "Ahlan ya user ya habibi." <<endl;
cout <<"what do you like to do today?" <<endl;
cout <<"please enter the message:" <<endl;
getline(cin,message);
for(int i=0;i<message.size();i++)
{
if(string(message[i]==32))
{
cout<<char(message[i]);
}
else if(string( message[i])>=110)
{
int x = int(message[i])-13;
cout<<char(x);
}
else
{
int x = string (message[i])+13;
cout<<char(x);
}
}
return 0;
}
E:\\ my programe \\ quiz \\ main.cpp | 20 |错误:没有匹配的函数调用'std :: __ cxx11 :: basic_string <char> :: basic_string(char&)'|
E:\\ my programe \\ quiz \\ main.cpp | 20 |错误:从'char'到'const char *'的无效转换[-fpermissive] |
E:\\ my programe \\ quiz \\ main.cpp | 27 |错误:没有匹配的函数调用'std :: __ cxx11 :: basic_string <char> :: basic_string(char&)'|
E:\\ my programe \\ quiz \\ main.cpp | 27 |错误:从'char'到'const char *'的无效转换[-fpermissive] |
std::string::operator[]
返回char&
引用。 您正在尝试构造具有单个char
值作为输入的临时std::string
对象,但是std::string
没有任何仅将单个char
作为输入的构造函数。 这就是为什么您会出错。
即使可以从单个char
构造std::string
,也无论如何都不能将std::string
与整数进行比较。
您根本不需要所有这些string()
(和char()
)强制转换(顺便说一句,您的第一个string()
强制转换始终是格式错误的)。 char
是数字类型。 您可以比较一个char
直接值为整数,并添加/直接从减和整数/ char
值,以产生新的char
值。
尝试以下方法:
#include <iostream>
using namespace std;
int main()
{
string message;
cout << "Ahlan ya user ya habibi." << endl;
cout << "what do you like to do today?" << endl;
cout << "please enter the message:" << endl;
getline(cin, message);
for(int i = 0; i < message.size(); i++)
{
if (message[i] == 32)
{
cout << message[i];
}
else if (message[i] >= 110)
{
char x = message[i] - 13;
cout << x;
}
else
{
char x = message[i] + 13;
cout << x;
}
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.