0

I've been developing a program in C# that encodes characters into their values (e.g, A: 65). However, I'm getting a debug error in the decoding event that states that the input string was not in a correct format. Will somebody try to help me please? Thank you.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Decode_Project
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string message = encoderBox.Text;
            decoderBox.Text = "";
            for (int i = 0; i < message.Length; i++)
            {
                int code = message[i];
                decoderBox.Text += String.Format("{0} ", code);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string[] messageCodes = decoderBox.Text.Split(' ');
            int[] codes = new int[messageCodes.Length];
            char[] letters = new char[codes.Length];
            for (int i = 0; i < codes.Length; i++)
            {
                codes[i] = int.Parse(messageCodes[i]);
                letters[i] = Convert.ToChar(codes[i]);
                encoderBox.Text = "";
                encoderBox.Text += letters[i];
            }

        }
    }
}
user3587709
  • 89
  • 1
  • 6
  • When you get the error, look at the `messageCodes` current value, it's probably not a number (or at the line you get the error, but I very much suspect it's your `int.Parse`). As a side note : you're overwriting `encoderBox` value each time, the final result will only be the last letter. As a bigger side note, `char`s are implicitly `int`s, so you can pretty much reduce all your code to `int[] codes = decoderBox.Text.Select(c => (int)c).ToArray();` – Pierre-Luc Pineault May 05 '14 at 03:10

1 Answers1

1

Let's say your input is ABC, after clicking on button1, your encoded text will be "65 66 67 ". (Notice the extra space at the end of the string.)

So when you click on button2, you will get:

messageCodes[0]: "65"
messageCodes[1]: "66"
messageCodes[2]: "67"
messageCodes[3]: ""    // <-- An extra empty string... Bad!

And when you do the int.Parse for the last item (the empty string), it will fail.

What you need to do is to trim the text before splitting it, as in:

string[] messageCodes = decoderBox.Text.Trim().Split(' ');

Also, as an aside, you should move the encoderBox.Text = ""; out of the for loop in order for it to work properly, as in:

encoderBox.Text = "";

for (int i = 0; i < codes.Length; i++)
{
    codes[i] = int.Parse(messageCodes[i]);
    letters[i] = Convert.ToChar(codes[i]);
    encoderBox.Text += letters[i];
}
SF Lee
  • 1,767
  • 4
  • 17
  • 32