How to fix this error "Can not convert from 'int' to 'char []'

4

Why is this error displayed? I believe the logic is right.

    
asked by anonymous 07.10.2017 / 23:04

2 answers

6

Formatting output

The first argument of the WriteLine method must be a string.

This string can contain markers to insert the following arguments into it:

Console.WriteLine("{0} {1} {2}", centena, dezena, unidade);

About error

The given error occurs because the WriteLine method has more than one way to be called. One of these forms receives char[] in the first argument, followed by two int s. What happens is that the compiler is evaluating the possible alternatives, and he thought it was the one you wanted to call.

    
07.10.2017 / 23:06
4

See documentation for this method .

There are several overloads to call you, each dealing with the information in a different way. Most are for basic types of language and as seen can only accept one argument.

The overhead that accepts multiple arguments can not be used directly, the first argument must be a string with the formatting that will be applied to the content and then the arguments that should be printed using this formatting. This is the one you should use.

There is a one that accepts more than one argument . Since this overload accepts int as the second and third argument, it is the one closest to what it looks like it needs, so the compiler mistakenly chooses this one.

This is called betterness .

In this case the ideal is to use string interpolation, avoid a lot of problem and become more readable (there are those who disagree). So:

using static System.Console;

public class Program {
    public static void Main() {
        WriteLine("Digite um número com três dígitos");
        if (int.TryParse(ReadLine(), out var numero) && numero < 10000) {
            WriteLine($"{numero / 100} {(numero % 100) / 10} {(numero % 100) % 10}");
        }
    }
}

See running on .NET Fiddle . Also I placed GitHub for future reference .

I fixed other code problems and made it more efficient and simple.

    
07.10.2017 / 23:09