-2

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);
    }
Danilo
  • 1
  • 1

2 Answers2

3

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.

Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
Sean
  • 60,939
  • 11
  • 97
  • 136
1

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

Caius Jard
  • 72,509
  • 5
  • 49
  • 80