Why can’t I read a string on the console?

Asked

Viewed 1,176 times

1

I’m trying to read a string typed into the console, which is halfway through the code, but what happens is it goes right through and displays the final information.

using System;

namespace Viernes
{
    class Program
    {
        static void Main(string[] args)
        {
            int xDig = -1, yDig = -1;
            char pCardeal = 'N';
           //Verificando a validade

            while (xDig < 0 && yDig < 0)
            {
                Console.Write("Digite as coordenadas \nx: ");
                xDig = Convert.ToInt32(Console.ReadLine());

                Console.Write("y: ");
                yDig = Convert.ToInt32(Console.ReadLine());
            }
            Console.Write("Cardeal 'N' 'S' 'L' 'O': ");
            pCardeal = Convert.ToChar(Console.Read());
            pCardeal = Char.ToUpper(pCardeal);

            //Comandos
            Console.WriteLine("Digite alguns comandos, 'E'squerda, 'D'ireita, 'A'vançar.");
            string str = Console.ReadLine();

            str = str.ToUpper();
            char[] Comands = str.ToCharArray();

            //Obj
            SpaceCar sp = new SpaceCar(xDig, yDig, pCardeal);

            foreach (var separaLetras in Comands)
            {
                switch (separaLetras)
                {
                    case 'E':
                        sp.girarEsquerda();
                    break;
                    case 'D':
                        sp.girarDireita();
                    break;
                    case 'A':
                        sp.avancarBloco(xDig, yDig);
                    break;
                }
            }
            //Imprimindo Destino
            Console.Write("Coordenadas: {0}{1}{2}", sp.PosicaoX,sp.PosicaoY, sp.PosicaoCardial);
            Console.WriteLine("Press Any Key to Exit");
            Console.ReadKey();
        }
    }
}

Code in the Pastebin

Complement to class SpaceCar in another Pastebin.

  • Hello. Why not edit your question and put the relevant code part into the question instead of pasting the link to the Pastebin?

  • Your code doesn’t even compile. Where is the Spacecar class? If it is not absolutely necessary for the code, then you could take it out to post here. http://answall.com/help/mcve

  • The class is required. I put the code at the top and it works, but I need this insertion to be done in the middle of the code.

  • If we can’t even test your code it’s hard to help. You have to put in complete, minimal, verifiable code. There are other problems that make your code even run. It would be good to give more details of how to reproduce the problem too.

  • Follow Spacecar code http://pastebin.com/Nw7qs6Pt

  • on the line pCardeal = Convert.ToChar(Console.Read()); the method Read does not wait for something to be typed, it picks up what has already been typed. Or you need to make a loop to pick up what will still be typed, or better yet, use the ReadKey(flase) in place, only then you will have to interpret the return that is of class ConsoleKeyInfo, ie returns the information of the key and not of the typed Character, needs a "conversion". If you find it too complicated and the ReadLine is enough, use it instead. It seems that this change solves the problem you have just described.

  • It had already tested Readline E did not work Console.Writeline("Type some commands, 'E'squerda, ’D'ireita, 'A'vançar."); string str = Console.Readline(); str.Toupper(); char[] Comands = str.Tochararray();

  • There is no reason for the ReadLine() not working. If it worked on others, it has to work on this.

  • @Pegasus Take a look at [tour]. You can accept an answer if it solved your problem. You can vote for every post on the site as well. Did any help you more? You need something to be improved?

Show 4 more comments

2 answers

1

Use Console.ReadLine() and not Console.ReadKey()

1

Your code has some problems, but I’ll just answer your question.

A minimal, complete and verifiable example code could have been written as the example below that demonstrates the solution.

using static System.Console;
using static System.Convert;

public class Program {
    public static void Main() {
        Write("Cardeal 'N' 'S' 'L' 'O': ");
        var pCardeal = char.ToUpper(ToChar(ReadKey(false).Key.ToString()));
        WriteLine($"PosicaoCardinal {pCardeal}");
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also I put on Github for future reference.

The problem I could understand was that I was using the method Console.Read() that does not wait for a key to be typed. It takes the character that is in the buffer, probably from the keyboard. The solution is to use a Console.ReadKey(false) who catches the key that was triggered. That is why it is necessary to treat your return as a key through the structure ConsoleKeyInfo. But it is possible to treat it easily with the ToString(), as shown above.

Has a partially refactored code and working on . NET Fiddle. For technical problem of it, can not test properly, so I tested with the compiler on my machine.

Anyway it gets weird having two fingerings waiting for a ENTER to finish typing after one that does not wait and then another that waits again. If you want to keep the pattern use a Console.ReadLine() in place of Console.ReadKey(). If you want to read one string, then read a string, and this is done with Console.ReadLine():

using static System.Console;
using static System.Convert;

public class Program {
    public static void Main() {
        Write("Cardeal 'N' 'S' 'L' 'O': ");
        var pCardeal = char.ToUpper(ToChar(ReadLine()));
        WriteLine($"PosicaoCardinal {pCardeal}");
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

  • I forgot to put Line after Read. 'pCardeal = Convert.Tochar(Console.Readline();' Thanks for the help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.