Question

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];
            }

        }
    }
}
Was it helpful?

Solution

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];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top