Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implicitly convert type string to int

Tags:

c#

parsing

    Console.WriteLine ("Please enter some numbers");
        int sum = 0;
        for(;;)
        {
            string input = Console.ReadLine ();
            if (string.IsNullOrEmpty (input))
            {
                break;
            }
            int inputParsed = int.Parse (input.ToString ());
            int sumParsed = int.Parse (sum.ToString ());
            sum = sum + input; // throws an error here

            Console.WriteLine (sum);

I want my programme to show the sum of all numbers entered by user, by even though I have parsed all the variables needed, it throws an "cannot implicitly convert type 'string' to 'int'" error. What's wrong?

like image 564
ltantonov Avatar asked Jul 06 '26 14:07

ltantonov


2 Answers

sum = sum + input; //throws an error here

should be:

sum = sum + inputParsed ;

You are using the original input instead of the parsed value. And you don't need sumParsed because you just keep the total sum in sum and you do no need to cast the int to a string and then parse it back to an integer.

like image 53
aweis Avatar answered Jul 09 '26 05:07

aweis


to check if the input of the user is right i would prefer

int userInput = 0;
if( int.TryParse( input, out userInput ) == false )
{
     break;
}

This is just an advise and not directly a solution to your problem. There are enough answers =)

like image 34
Viper Avatar answered Jul 09 '26 03:07

Viper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!