Home   Cover Cover Cover Cover
 

Telefonbuch

A08.cs
using System;
using System.Collections;
using System.IO;

// Reads a file with names and phone numbers and builds a phone book from it.
// Returns the phone number for a given name.
class PhoneBook {
  
  static void Main(string[] arg) {
    Hashtable tab = new Hashtable();
    string fileName;
    if (arg.Length > 0) fileName = arg[0]; else fileName = "phoneBook.txt";
    //--- read the phone book
    StreamReader r = File.OpenText(fileName);
    string line = r.ReadLine();  // line format: name = number
    while (line != null) {
      int pos = line.IndexOf('=');
      string name = line.Substring(0, pos).Trim();
      int phone = Convert.ToInt32(line.Substring(pos+1));
      tab[name] = phone;
      line = r.ReadLine();
    }
    r.Close();
    //--- aks for phone numbers
    for (;;) { // empty name terminates the loop
      Console.Write("name> ");
      string name = Console.ReadLine().Trim();
      if (name == "") break;
      object phone = tab[name];
      if (phone == null)
        Console.WriteLine("-- not found in phone book");
      else
        Console.WriteLine(phone);
    }
  }
}