Home > Mobile >  Reading in an integer array, and stopping when a string is entered
Reading in an integer array, and stopping when a string is entered

Time:05-24

int [] arr = new int [100];
int count = 0;
int val;
arr[count] = 0;

while(count < arr.Length && (int.TryParse(arr[count], out val)))
{
    arr[count] = Convert.ToInt32.Console.ReadLine();
}

I want the user to enter values for an array, and when they enter 'exit' the while loop breaks

CodePudding user response:

You should read input first using do..while loop and use exit condition to get out of while loop if user enters exit

do
{
   string input = Console.ReadLine();  //Read input from user
   if(input == "exit")  //exit condition
     break;
   if(int.TryParse(input, out int intData))
       arr[count  ] = intData;
}while(count < arr.Length);
  • Related