C#, Getting user value and resetting it

Viewed 248

Right now my problem is getting choice 2 to save and rewrite what was written in choice 1. Choice 3 should then reset everything. Right now i tried with at if inside an if and still not getting it to work.

while (true)
{
    Console.WriteLine("\tWelcome to my program"); // Makes the user select a choice
    Console.WriteLine("[1] To write");
    Console.WriteLine("[2] To see what you wrote");
    Console.WriteLine("[3] Reset");
    Console.WriteLine("[4] End");

    string choice = Console.ReadLine();
    string  typed = ("");

    if (choice == "1") // If 1 program asks for text
    {
        Console.WriteLine("Thank you for your choice, input text"); 
        typed = Console.ReadLine(); 
    }
    else if (choice == "2") // Is supposed to say "You wrote, and what user wrote"
    {
        Console.WriteLine(typed);
    }                            
    else if (choice == "3") //  Resets the text so if 2 is selected it would say "You wrote,     "
    {
        Console.WriteLine("Reset. Would you like to try again?");
        typed = "";
    }
    else if (choice == "4") // Ends program
    {
        break;
    }
    else
    {
        Console.WriteLine("Input not computing, try again");
    }
1 Answers

Your issue is as follows.

First, you are looping your entire program through a while (true) loop. Once the user choice is made, the program will go back to the while (true). Note also that string typed is defined inside the loop. Therefore, every time the loop is called (which is every choice made), the program resets the value of 'typed'.

To fix this, introduce string typed outside the loop.

string typed = "";

while (true)
{
    //choices and stuff goes back here
}

Edit: I noticed this comment of yours //Is supposed to say "You wrote, and what user wrote on choice 2. Note that your code in choice 2 won't output "You wrote" + typed. To correct that, change Console.WriteLine(typed); to Console.WriteLine("You wrote, " + typed);.

Related