Home > Software design >  how can i enter a value in LastName after i Enter a variable in the char variable?
how can i enter a value in LastName after i Enter a variable in the char variable?

Time:02-20

        string FirstName, LastName;
        char MiddleInitial;
      
          Console.Write("Enter  first name: ");
          FirstName = Console.ReadLine();



          if (FirstName.Equals("null"))
          {
              Console.Write("Insert middle initial: ");
              Console.Write("\nInsert last name: \n");

          }
          else
          {
              Console.Write("Insert middle initial: ");
            MiddleInitial = (char) Console.Read();
            Console.Write("Enter  last name: ");
            LastName = Console.ReadLine();
            
            Console.ReadKey();

I can't enter the lastname variable at the last part of my code. Anyone there more knowledgable who can answer my concern?

The output always went like this: Enter first name:Jason Insert middle initial: f Enter last name:

After i press one letter it goes back to the IDE

The program output should be like this: Enter first name:Joshua Insert middle initial:F Enter last name:Capili


Enter  first name:null 
Insert middle initial:
Enter  last name:

CodePudding user response:

I try to execute your code, in my VS it works. Try this code:

 MiddleInitial = Console.ReadKey().KeyChar;

Or this:

 MiddleInitial = Console.ReadLine()[0];

CodePudding user response:

This is happening because Console.Read() appends a new line to the input. When you subsequently do Console.Readline() there is already a line in the buffer so it sets LastName to whatever comes after the first character you type, even if it is empty string.

You can use ReadLine() for the middle initial (as a string) and just take the first character.

  •  Tags:  
  • c#
  • Related