The method Console.Read() don't returns a string

338 Views Asked by At

When I declare a variable "string x = Console.Read();" the message is shown: "Cannot implicitly convert type 'int' to 'string'".

To test this, I made the console show the value I wrote in the input. I typed 5 in the input but the console showed me 53.

Why is this happening?

thank you in advance

public static void a21() {

        System.Console.Write("Deseja ver a sequência até qual termo? ");
        int n = Convert.ToInt32(Console.Read());
        int count = 0;

        int[] vetor = new int[n];

        while (count < n)
        {
            int quadrado = count * count;
            vetor[count] = quadrado;
            count++;
        }

        for (var i = 0; i < n; i++)
        {
            System.Console.WriteLine(vetor[i]);
        }
        System.Console.WriteLine(n);
    }
2

There are 2 best solutions below

0
Sean On

Console.Read returns an int containing the character that was read, or -1 if nothing could be read.

It does not return a string.

If you want to read a string then use Console.ReadLine.

0
Caius Jard On

I typed 5 in the input but the console showed me 53.

Because Console.Read() read your char '5', and returned it as an integer 53, which is the decimal position on the ASCII table for char '5':

enter image description here

Convert.ToInt did nothing to it, because it was already an int, so sending 53 into the conversion returns it as 53.

If you print it (your code doesn't but I assume you did so to debug this), you get 53