如何在c++中与用户输入交换整个句子的字符



我想在

中获取用户的输入
char input[200];

然后我要根据

交换输入的每个字符
a='y'; b='b'; c='j'; d='m'; e='x'; f='f'; g='w'; h='i';
i='v'; j='c'; k='l'; l='u'; m='t'; n='a'; o='k'; p='h';
q='d'; r='p'; s='s'; t='n'; u='z'; v='q'; w='e'; x='r';
y='o'; z='g';

例如输入

hello

输出将是

ixuuk

我想在c++中使用for循环和数组编写代码。

我建议您使用查找数组:

char output = conversion[input_char];

您可以使用一些算术运算将数组简化为26个字母:

char output = conversion[input_char - 'a'];

表达式input_char - 'a'使得字母a表示conversion数组中的第一个槽位。

下面是一个数组的例子:

static const char conversion[] =
{'b', 'y', 'c', 'k', 'f', /*...*/, 'a'};

使用上面的代码,如果输入是a,输出将是b。输入b,输出y,以此类推。

不需要交换。记住,交换会改变值。我相信你想要转换或者翻译

下面是一个示范程序,展示了如何做到这一点

#include <iostream>
#include <cstring>
#include <utility>
int main() 
{
    std::pair<const char *, const char *> cipher =
    {
        "abcdefghijklmnopqrstuvwxyz",   
        "ybjmxfwivclutakhdpsnzqerog"    
    };
    const size_t N = 200;
    char input[N];
    input[0] = '';
    std::cin.getline( input, sizeof( input ) );
    std::cout << '"' << input << '"' << std::endl;
    for ( char *p = input; *p; ++p )
    {
        if ( const char *q = std::strchr( cipher.first, *p ) )
        {
            *p = cipher.second[q - cipher.first];
        }
    }
    std::cout << '"' << input << '"' << std::endl;
    return 0;
}

程序输出为

"Hello"
"Hxuuk"

您还可以使用tolowertoupper函数将源字符串的初始字符转换为某些大小写。

问题解决了

#include <iostream>
#include <cstring>
#include <utility>
int main() 
{
    std::pair<const char *, const char *> 
cipher ("abcdefghijklmnopqrstuvwxyz",   
        "ybjmxfwivclutakhdpsnzqerog");

    const size_t N = 200;
    char input[N];
    input[0] = '';
    std::cin.getline( input, sizeof( input ) );
    std::cout << '"' << input << '"' << std::endl;
    for ( char *p = input; *p; ++p )
    {
        if ( const char *q = std::strchr( cipher.first, *p ) )
        {
            *p = cipher.second[q - cipher.first];
        }
    }
    std::cout << '"' << input << '"' << std::endl;
    return 0;
}

特别感谢来自莫斯科的@Vlad

我建议你使用嵌套循环。创建一个包含所有字母的字符串数组。然后创建另一个字符串数组,其中包含您想要用字母更改的所有字符,其顺序与字母相同。

    #include <iostream>
    using namespace std;
    int main()
    {
        string alphabets="abcdefghijklmnopqrstuvwxyz" , 
        cipher="ybjmxfwivclutakhdpsnzqerog" , word , newword="" ;
        cin>>word;
        newword=word;
        for(int i=0;i<26;i++)
        {
            for(int j=0;j<26;j++)
            {
                if(word[i]==alphabets[j])
                {
                    newword[i]=cipher[j];
                    break;
                }
            }
        }
        cout<<newword;
        return 0;
    }

最新更新