0

I am making a caesar cipher and am trying to convert the char value of each letter into an int so the shift value can change it.

for (int i = 0; i < plainTextInput.Length; ++i)
{
   chars[i] = ((int)chars[i]) + shiftAmount;         
}

It says it cannot convert int into char. How do i fix this problem?

1
  • 2
    It seems like chars[] is an array of chars. If so, you need to cast it back to a char: chars[i]=(char)((int)chars[i])+shiftAmount; Commented Sep 30, 2011 at 2:35

3 Answers 3

1

You have to explicitly cast it back:

for (int i = 0; i < plainTextInput.Length; ++i)
{
   chars[i] = (char)(((int)chars[i]) + shiftAmount);         
}

However, you're going to run into trouble pretty quickly once you shift past z.

Sign up to request clarification or add additional context in comments.

Comments

0

When I compile that code, I get the following error message:

Cannot implicitly convert type 'int' to 'char'. An explicit conversion exists (are you missing a cast?)

Why yes, you are missing a cast:

chars[i] = (char)(((int)chars[i]) + shiftAmount);

Comments

0

By explicitly casting:

chars[i] = (char)(((int)chars[i]) + shiftAmount);     

I'd rewrite your loop:

var enciphered = chars.Select(c => (char)((int)c + shiftAmount)).ToArray();

What are you planning to do if you shift to a non-printable character? Standard Caesar cipher wraps around. You should incorporate that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.