简体   繁体   中英

How to do user input in a dictionary in C#?

I want to make a dictionary which takes user input with space. The dictionary takes input a string and integer.

I tried by giving input by array but don't know how to do user input in two arrays simultaneously with space.

Dictionary<string, int> Directory = new Dictionary<string, int>();
int n = int.Parse(Console.ReadLine());
string[] name = new string[n];
int[] phone_no = new int[n];
for (int i = 0; i < n; i++)
}
    name[i] = Console.ReadLine();
    phone_no[i] = int.Parse(Console.ReadLine());
}
for (int i = 0; i < n; i++)
{
    Directory.Add(name[i], phone_no[i]);
}

I want help for doing user input like:

1.Sam 12345678

2.Harry 25468789

Note that a phone number is not an int, but a string. It may start with a zero, and if you'd parse that to an int, you lose the leading zero (0123456789 becomes 123456789). Also, I'd consider "+31 (0)6-12345678" a valid phone number.

Here's an example that does what you want. It keeps requesting input until the user types 'exit' and updates the name with the phonenumber.

public static void Main()
{
    var directory = new Dictionary<string, string>();

    // Keep requesting inputs
    while (true)
    {
        string input = Console.ReadLine();

        // provide a possibility to break the loop.
        if (input == "exit")
        {
            break;
        }

        string[] items = input.Split(' ', StringSplitOptions.RemoveEmptyEntries);
        if (items.Length != 2)
        {
            Console.WriteLine("Expecting '{Name} {Phonenumber}'");
            continue;
        }

        directory[items[0]] = items[1];
    }

    // TODO: Do something with directory
}

You can split the line using String.Split() ie

var pair = Console.ReadLine().Split(' ');
Dictionary.Add(pair[0], int.Parse(pair[1]))
static void Main(string[] args)
    {
        Dictionary<string, int> Directory = new Dictionary<string, int>();
        Console.WriteLine("Enter the Number of inputs");
        int count = int.Parse(Console.ReadLine());
        for (int i = 0; i < count; i++)
        {
            Console.WriteLine("Enter the Name " + i + 1 + " : ");
            string Name = Console.ReadLine();
            Console.WriteLine("Enter the Age " + i + 1 + " : ");
            int Age = Convert.ToInt32(Console.ReadLine());
            Directory.Add(Name, Age);
        }
        Console.WriteLine("Press key to display the contents of your dictionary..");
        Console.ReadLine();
        foreach (var item in Directory)
        {
            Console.WriteLine("Name : " + item.Key);
            Console.WriteLine("Age : " + item.Value);
        }
        Console.ReadLine();
    }

Working Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM