【问题标题】:how to convert message to cipher message?如何将消息转换为密码消息?
【发布时间】:2018-09-05 04:07:06
【问题描述】:
#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|error: no matching function for call to 'std::__cxx11::basic_string::basic_string(char&)'|

E:\my programe\quiz\main.cpp|20|错误:从 'char' 到 'const char*' 的无效转换 [-fpermissive]|

E:\my programe\quiz\main.cpp|27|error: no matching function for call to 'std::__cxx11::basic_string::basic_string(char&)'|

E:\my programe\quiz\main.cpp|27|错误:从 'char' 到 'const char*' 的无效转换 [-fpermissive]|

【问题讨论】:

  • 这没什么大不了的,但除了答案的反馈之外,您应该考虑只使用 'n'' ' 而不是表示这些值的整数,因为它使您的代码更具可读性

标签: c++


【解决方案1】:

std::string::operator[] 返回一个char&amp; 引用。您正在尝试使用单个 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;
}

Live Demo

【讨论】:

    猜你喜欢
    • 2011-07-07
    • 2015-07-27
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 2013-07-12
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多