1

Am I going mad? Why does this return an exception!? Why can't it find the key? It's obviously there!

public class Spanning {
    Dictionary<string, City> graph = new Dictionary<string, City>();

    public static void Main(string[] args) {
        new Spanning().Parse("file.in");
    }

    public void Parse(string f) {
        string[] citySeparator = new string[] {"--"};
        using (StreamReader reader = new StreamReader(f)) {
            string line;
            while((line = reader.ReadLine()) != null) {
                if (!line.Contains("--")) {
                    graph[line] = new City {name = line.Substring(0, line.Length - 1)};
                } else {
                    string[] split = line.Split(citySeparator, StringSplitOptions.None);
                    City city1 = graph[split[0]];
                }
            }
        }
    }

    class City {
        Dictionary<City, int> links = new Dictionary<City, int>();
        public string name;

        public override string ToString() {
            return name;
        }
    }
}

Input file contains just two rows:

"San Diego" 
"San Diego"--"San Antonio" [1319]
3
  • 3
    What exception do you get?
    – Flat Eric
    Apr 4, 2014 at 12:09
  • 1
    Can you step through the code? Apr 4, 2014 at 12:10
  • 1
    Try putting a break point and see step by step what is going on.
    – Habib
    Apr 4, 2014 at 12:10

1 Answer 1

7

The first line of your file

"San Diego" 

has a space character between the last " and the newline.

Either fix you input file, or use Trim() to get rid of it:

...
if (!line.Contains("--")) {
    graph[line.Trim()] = new City {name = line.Substring(0, line.Length - 1)};
...
3
  • Oh my god! I *** missed that when using it as a key... Thank you!
    – Andreas
    Apr 4, 2014 at 12:19
  • 1
    It was helpful that you copied the additional whitespace into your question, too :-)
    – sloth
    Apr 4, 2014 at 12:21
  • I've found that this usually bites every developer at least once. After the first time, you start looking for extra whitespace. Apr 4, 2014 at 13:18

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.