Do you doubt about "insertion" of variables in the input command in C #?

0

Well, my question is, in C # I can use my "constants" be it of any kind on my output command, all normal.

However, if I use a "variable" of type int or double and put them in the input command of a Syntax error:

  

"Convert type 'string' to 'int'" or "Convert type 'string'   to 'int' ".

In the error message speaks for I convert, I have to always convert, why when I use string does not appear to convert synonymous?

Anyway, I can say this bullshit but I'm very good at programming and I would like to clarify this doubt.

    
asked by anonymous 16.05.2018 / 04:01

2 answers

1

The ReadLine() method contained within Console always returns a string ( See documentation ), so if your variable is not of type string conversion will be necessary;

The WriteLine() method, also contained in the Console class, receives parameters of several different types, see documentation

See an example:

Console.Write("Digite a nota: ");
if (!int.TryParse(Console.ReadLine(), out int nota))
    Console.WriteLine("Falha ao converter valor para inteiro");
else
    Console.WriteLine($"Nota digitada: {nota}");

With Console.Write() , an entry is being requested, below I try to do a conversion of the typed value to type int with int.TryParse , if the entry is successfully converted, the typed note is written on the screen, if Failure, this is informed to the user.

You can also check all of this in Console class documentation

    
16.05.2018 / 04:24
0

The Barbetta comment is the best, yet leaving it more streamlined.

The code is telling you that you do not understand what was typed above, because in the line

Console.Write ("Digite sua nota: ");

is receiving a String, however the variable that will receive what it has entered is expecting to receive an Int (number).

To fix this, simply convert the advertised to number, as follows:

Convert.ToInt32(Console.ReadLine());

So he will receive what was typed above and then convert what he received in number.

    
26.10.2018 / 01:10