Slateboard
Slateboard

Reputation: 1031

Which loop do I use to ask if a user wants to continue the program in C#

I made a program that asks for input and returns a value. After, I want to ask if the user wants to continue. But I don't know what to use.

Upvotes: 1

Views: 4839

Answers (7)

0xFF
0xFF

Reputation: 4178

Technically speaking, any loop will do it, a for loop for example (which is another way to write a while(true){;} )

    for (; true; )
    {
        //Do stuff
        if (Console.ReadLine() == "quit")
            {
            break;
        }
        Console.WriteLine("I am doing stuff");
    }

Upvotes: 0

Asad
Asad

Reputation: 21928

use Do While Loop. something similar will work

int input=0;
do
{  
  System.Console.WriteLine(Calculate(input)); 
  input =  GetUserInput();
} while (input != null)

Upvotes: 0

AxelEckenberger
AxelEckenberger

Reputation: 16926

This only allows 2 keys (Y and N):

ConsoleKeyInfo keyInfo;
do {
    // do you work here
    Console.WriteLine("Press Y to continue, N to abort");

    do {
        keyInfo = Console.ReadKey();
    } while (keyInfo.Key != ConsoleKey.N || keyInfo.Key != ConsoleKey.Y);
} while (keyInfo.Key != ConsoleKey.N);

Upvotes: 2

Lucas Jones
Lucas Jones

Reputation: 20183

I would use a do..while loop:

bool shouldContinue;
do {
    // get input
    // do operation
    // ask user to continue
    if ( Console.ReadLine() == "y" ) {
        shouldContinue = true;
    }
} while (shouldContinue);

Upvotes: 1

Lee
Lee

Reputation: 144126

A do-while loop is often used:

bool @continue = false;
do
{
    //get value
    @continue = //ask user if they want to continue
}while(@continue);

The loop will be executed once before the loop condition is evaluated.

Upvotes: 2

Nick Craver
Nick Craver

Reputation: 630379

You probably want a while loop here, something like:

bool doMore= true;

while(doMore) {
  //Do work
  //Prompt user, if they refuse, doMore=false;
}

Upvotes: 0

SLaks
SLaks

Reputation: 887285

You want to use a do / while loop, or an infinite while loop with a conditional break.

Upvotes: 3

Related Questions