0

Hey all, I've been making a caesar cipher but seem to have encountered a problem. My program reads an integer from a text file and stores it as the shift value. Then my goal was to add that shift value to the alphabet array. Here is a part of my code:

inFile.get (shift); 

    cout << "Original Alphabet: ";
    for(int i = 0; i < length; i++)
        cout << alphabet[i];
    cout << endl;

    cout << "Shift Value: " << shift << endl;

    cout << "Encrypted Alphabet: ";
    for(int i = 0; i < length; i++)
    {
        Caesar[i] = alphabet[(i + shift) % length];
        cout << Caesar[i];

My issue is that the shift value comes out as 4, however the caesar array comes out identical to the alphabet array.

3
Contributors
7
Replies
33
Views
2 Years
Discussion Span
Last Post by vmanes
0

I just used your code, and with shift of 4, the Caesar array is:
efghijklmnopqrstuvwxyzabcd

Just what it should be. What are you seeing as a problem?

0

There's no obvious error in the snippet of code you've posted.
A complete working example based on your code:

#include <iostream>

int main()
{
    using std::cout;
    using std::endl;

    const size_t length = 26;

    const char alphabet[length] = {
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
        'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
    };

    char Caesar[length] = {0};

    int shift = 4;

    cout << "Original Alphabet:  ";
    for(int i = 0; i < length; i++)
        cout << alphabet[i];
    cout << endl;

    cout << "Shift Value: " << shift << endl;

    cout << "Encrypted Alphabet: ";
    for(int i = 0; i < length; i++)
    {
        Caesar[i] = alphabet[(i + shift) % length];
        cout << Caesar[i];
    }

    std::cin.get();

    return 0;
}

/* 
Original Alphabet:  ABCDEFGHIJKLMNOPQRSTUVWXYZ
Shift Value: 4
Encrypted Alphabet: EFGHIJKLMNOPQRSTUVWXYZABCD
*/
0

I know that works fine, but that is not my full code. When I read from a file and try to execute the shift some of the letters are shifted incorrectly

0

You need to post the relevant code so that we can see where the actual problem is, not a snippet that works fine.

0

inFile.get (shift);
Is it that you are getting in the shift value as a character, but you are using as the number it represents?

Actually, that input gets a string. Do you convert it to integer somewhere you're not showing?

0

No I didn't convert it to an integer as I didn't know how. The inFile.get (int) doesn't work and when i made shift a char, it managed to work. I am able to get a semi functional program, however there are a few characters that are off.

0

Is there a reason you don's use:

int shift;
infile >> shift;

That would store the value as an integer.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.