Sam
Sam

Reputation: 193

Console hangs on newline after getting user input

I need this program to ask the user to input a number to add to an array. After they input the number, the console goes to a newline until you press another key, at which point it will do the same thing over again. I'm new to C# and I assume this has something to do with the fact that it's reading the enter key after the user inputs the information, so I need to use something equivalent to cin.ignore(), but I haven't been able to find anything that solves the issue.

public void InputSet()
{
    int userInput;

    do
    {
        C.Write("Enter an element (Enter to end): ");
        userInput = Convert.ToInt32(C.ReadLine()); // Read user input

        if (userInput < 1 || userInput > 50) // Check if in bounds
            C.WriteLine("Input is invalid. Enter from 1 to 50."); // Error message if out of bounds
        else
        {
            Array.Resize(ref arr, arr.Length + 1); // Expand array and then add it in
            arr[arr.Length - 1] = userInput;
        }
    } while(Console.ReadKey (true).Key != ConsoleKey.Enter); // If enter key is pressed, exit loop

Here is a video of the problem: Hanging on newline

Upvotes: 1

Views: 586

Answers (2)

Alex Leo
Alex Leo

Reputation: 2851

The console is not hanging - it is expecting an input in order to continue the while loop:

while(Console.ReadKey (true).Key != ConsoleKey.Enter);

I have tested the code and it works fine - Perhaps you might want to feedback the user in what action to take in order to finish or to continue.

        Console.WriteLine("Press enter to terminate or C to continue");
    } while (Console.ReadKey(true).Key != ConsoleKey.Enter); // If enter key is pressed, exit loop

Any key will do really.

Upvotes: 2

TheGeneral
TheGeneral

Reputation: 81573

I am not entirely sure i understand your question or the problem

However,

  1. You should probably be using a List instead of an array
  2. You should be using int.TryParse to validate user input
  3. You should probably be using Console.ReadLine instead of ReadKey
  4. You can check result == string.Empty to exit

Example

var list = new List<int>();

while (true)
{
   Console.Write("Enter an element (Enter to end): ");
   var result = Console.ReadLine();

   if (result == string.Empty) break;
   if (!int.TryParse(result, out var value))
   {
      Console.WriteLine("You had one job...");
      continue;
   }
   list.Add(value);
} 

Console.WriteLine(string.Join(", " , list));

Console.ReadKey();

Output

Enter an element (Enter to end): 2
Enter an element (Enter to end): 3
Enter an element (Enter to end): 4
Enter an element (Enter to end): 6
Enter an element (Enter to end): f
You had one job...
Enter an element (Enter to end):
2, 3, 4, 6

Upvotes: 2

Related Questions