2

I am currently working on a programming language, and my friend asked me to convert it to a console application and, so far it hasn't been going well

if (input.Contains(""))
{
    string name = input.Substring(0, 3);
    string value = input.Substring(4);
    Console.WriteLine("Name:" + name + " " +  "Value:" + value);
    vars[Convert.ToInt32(name)] = value;
}

The line that says vars[Convert.ToInt32(name)] = value; has been giving me errors when I run it the first 3 lines above it work this is an example of what I would type in the console str Hello and it would print Name:str Value:Hello but then it stops the program and shows me this error

Input string was not in a correct format.

I'm not to familiar with this error but if you have ever programmed in Lua this is what im trying to accomplish

elseif line:match("^int") then
    local n, v = line:match("^int (.+) = (%d+)")
    vars[n] = v

I always had a problem with arrays in C#, so if you could please tell me whats wrong it would help me a lot, Thanks in advance.

4
  • 1
    Convert.ToInt32(name) if name is not numeric (which most likely it isn't, given the variable name name) within the range of int then the format is incorrect. Commented Jan 25, 2016 at 4:34
  • What is the expected value for Convert.ToInt32(name)? Commented Jan 25, 2016 at 4:36
  • Note that input.Contains("") will always return true (or throw an exception if input is null). Commented Jan 25, 2016 at 4:37
  • If that's regular expressions in your lua code you might want to use the Regex class Commented Jan 25, 2016 at 4:46

2 Answers 2

5

It sounds like you actually want a Dictionary to hold a key-value pair of name and value. You can only use an int for an index on an array, so a dictionary allows you to use string values.

var inputDictionary = new Dictionary<string,string>();
if (input.Contains(""))
{
    string name = input.Substring(0, 3);
    string value = input.Substring(4);
    Console.WriteLine("Name:" + name + " " +  "Value:" + value);
    inputDictionary.Add(name, value);
}
Sign up to request clarification or add additional context in comments.

Comments

1

Instead you can have a HashTable like below

        Hashtable hashTable = new Hashtable();
        if (input.Contains(string.Empty))
        {
            hashTable.Add(input.Substring(0, 3), input.Substring(4));
        }

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.