Home > Back-end >  Is there a way to save what the user has inputted via "Console.ReadLine()" in C#?
Is there a way to save what the user has inputted via "Console.ReadLine()" in C#?

Time:07-24

I'm trying to make a program on Microsoft Visual Studio where it would create a list of things that the user input and put them in order from 1 to x (x being how every many things you input). It's a little bit hard to explain but this is roughly how it works: you would input a number (for example "7") and it would ask you to type 7 different things into the console. Once you're finished, it would randomly pick two different things that you entered and it would ask you which one you liked more. Eventually, using a bracket like system it would narrow it down to a winner and would make a list from the best to worst.

This is my code for when you enter x number of things for the list:

int numberOfThings = Convert.ToInt32(Console.ReadLine()); 
int times = 0;
do
{
    Convert.ToString(Console.ReadLine());
    times = times   1;
}
while (numberOfThings != times);

The code works well but I'm having a hard time figuring out how to save the inputs from "Console.ReadLine()" to strings. There could be an easy answer for this but I'm fairly new to C# and I guess coding in general. Thank you in advance :)

CodePudding user response:

You can make use of an array to store the user inputs. I'll let you figure out randomly picking the inputs from there, but here's the code to store into an array:

int numberOfThings = Convert.ToInt32(Console.ReadLine()); 
// Add the array here
string[] inputs = new string[numberOfThings];
int times = 0;
do
{
    // Access an element of the array at position `times`, and store the value from the user there
    inputs[times] = Console.ReadLine();
    times = times   1;
}
while (numberOfThings != times);

// Just putting this here to show you more examples of how to use an array (you can also use foreach as well)
for (int i = 0; i < inputs.Length; i  )
{
    Console.WriteLine(inputs[i]);
}

CodePudding user response:

Cant you save the inputs into a List ? Using add on each input retrieved.

  •  Tags:  
  • c#
  • Related