Как мне увеличить буквы в C ++? - PullRequest
8 голосов
/ 13 декабря 2011

Я создаю Цезарь-шифр в c ++ и не могу понять, как увеличить букву.

Мне нужно увеличивать букву на 1 каждый раз и возвращать следующую букву в алфавите.Что-то вроде следующего, чтобы добавить 1 к 'a' и вернуть 'b'.

char letter[] = "a";
cout << letter[0] +1;

Ответы [ 8 ]

6 голосов
/ 13 декабря 2011

Этот фрагмент должен помочь вам начать.letter - это char, а не массив char s или строка.

static_cast гарантирует, что результат 'a' + 1 будет рассматриваться как char.

> cat caesar.cpp          
#include <iostream>

int main()
{
    char letter = 'a';
    std::cout << static_cast<char>(letter + 1) << std::endl;
}

> g++ caesar.cpp -o caesar
> ./caesar                
b

Берегитесь, когда доберетесь до 'z' (или 'Z'!) И удачи!

4 голосов
/ 13 декабря 2011

Работает как есть, но поскольку добавление переводит выражение в int, вы хотите снова преобразовать его в char, чтобы ваш IOStream отображал его как символ, а не число:

int main() {
   char letter[] = "a";
   cout << static_cast<char>(letter[0] + 1);
}

Выход : b

Также добавьте логику обтекания (чтобы letter[0] равнялось z, вы устанавливали a вместо увеличения) и учитывали регистр.

2 голосов
/ 13 декабря 2011

Письмо ++ работает? В целом, char является числовым типом, поэтому он будет увеличивать ascii code . Но я считаю, что это должно быть определено как char letter, а не массив. Но остерегайтесь добавлять один к 'Z'. Вы получите '[' = P

#include <iostream>

int main () {
    char a = 'a';
    a++;
    std::cout << a;
}

Кажется, это хорошо работает;)

1 голос
/ 28 декабря 2017

Вы можете использовать 'a' + ((буква - 'a' + n)% 26); при условии, что после 'z' вам нужно 'a', то есть 'z' + 1 = 'a'

    #include <iostream>

    using namespace std;

    int main()
    {
       char letter='z';
       cout<<(char)('a' + ((letter - 'a' + 1) % 26));

       return 0;
    }

См. https://stackoverflow.com/a/6171969/8511215

1 голос
/ 25 ноября 2014

waleed @ waleed-P17SM-A: ~ $ nano Good_morning_encryption.cpp waleed @ waleed-P17SM-A: ~ $ g ++ Good_morning_encryption.cpp -o Good_morning_encryption.out waleed @ waleed-P17SM-A: ~ $ ./Good_morning_encryption.out Введите текст: waleed Зашифрованный текст: jnyrrq waleed @ waleed-P17SM-A: ~ $ cat Good_morning_encryption.cpp

    #include <iostream>
    #include <string>

    using namespace std;


    int main() {

    //the string that holds the user input
    string text;
    //x for the first counter than makes it keeps looping until it encrypts the user input
    //len holds the value (int) of the length of the user input ( including spaces)
    int x, len;

    //simple console output
    cout << "Enter your text:";
    //gets the user input ( including spaces and saves it to the variable text
    getline(cin, text);
    //give the variable len the value of the user input length
    len = (int)text.length();
    //counter that makes it keep looping until it "encrypts" all of the user input (that's why it keeps looping while its less than len
    for(x = 0; x < len; x++) {
    //checks each letts (and spaces) in the user input (x is the number of the offset keep in mind that it starts from 0 and for example text[x] if the user input was waleed would be w since its text[0]
    if (isalpha(text[x])) {
    //converts each letter to small letter ( even though it can be done another way by making the check like this if (text[x] =='z' || text[x] == 'Z')
    text[x] = tolower(text[x]);
    //another counter that loops 13 times
    for (int counter = 0; counter < 13; counter++) {

    //it checks if the letts text[x] is z and if it is it will make it a
    if (text[x] == 'z') {

    text[x] = 'a';

    } 
    //if its not z it will keeps increamenting (using the loop 13 times)
    else {


    text[x]++;

    }

    }
    }
    }
//prints out the final value of text
    cout << "Encrypted text:\n" << text << endl;
    //return 0 (because the the main function is an int so it must return an integer value
    return 0;

    }

Примечание: это называется шифрование caeser cipher, оно работает так:

АБВГДЕЖЗИКЛМНОПРСТУФХЧШЭЮЯ NOPQRSTUVWXYZABCDEFGHIJKLM так, например, меня зовут Валид это будет записано как: JNYRRQ так что просто добавьте 13 букв к каждой букве

Я надеюсь, что это помогло

1 голос
/ 13 декабря 2011

Это работает, но не забывайте, что если вы увеличиваете 'z', вам нужно получить 'a', поэтому, возможно, вам следует пройти мимо функции проверки, которая выдает 'a', когда вы получаете 'z'.

1 голос
/ 13 декабря 2011
char letter = 'a'; 
cout << ++letter;
0 голосов
/ 13 декабря 2011

приведите букву [n] к байту * и увеличьте ее ссылочное значение на 1.

...