CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 17

Threaded View

  1. #13
    Join Date
    Feb 2011
    Location
    United States
    Posts
    1,016

    Re: Cannot implicitly convert type "string" to "int"

    Quote Originally Posted by Krunchyman View Post
    The code I'm using now is exactly the same as the last one I posted.

    (1) The error is a compiler error.
    (2) The exact error message is "Cannot implicitly convert type "string" to "int".
    (3) Line 21, column 25. It's the "guess = Console.WriteLine();" line.
    Sorry for getting distracted with the goto discussion. The problem is as follows:

    guess is declared as an int. Console.ReadLine() returns a string. You are trying to assign a variable of one type to a variable of a different type. In general, this is not allowed. You must first convert the string to an int. Do this like:

    Code:
    guess = Int32.Parse(Console.ReadLine());
    Or even better

    Code:
    bool valid = false;
    while( !valid )
    {
        //Try to convert the string typed in to an integer and store it in guess
        //Valid will be assigned true only if this parsing succeeds.
        valid = Int32.TryParse(Console.ReadLine(), out guess);
    }
    The difference between Int32.Parse(string) and Int32.TryParse(string, out int) is that the former will convert the string to an int and throw an exception if given invalid input. The latter will convert a string to an int and give you a return value (bool) indicating whether or not the parsing was successful.
    Last edited by BioPhysEngr; December 1st, 2011 at 10:14 PM. Reason: typos
    Best Regards,

    BioPhysEngr
    http://blog.biophysengr.net
    --
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured