Cannot implicitly convert type "string" to "int"
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 17

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

  1. #1
    Join Date
    Jun 2011
    Posts
    33

    [Resolved] Cannot implicitly convert type "string" to "int"

    Since I'm still fairly new to C#, I decided to go back to the basics.

    Here I have a fairly simple problem with a basic number game I'm programming in C#. Basically, the game will generate a random number and if the user guesses the correct number, it will state that the user has won. Otherwise, it tells the user that it must guess again and it restarts the program.

    This is the source code so far. I have just one bug and it's the classic "cannot implicitly convert type "string" to "int" bug. "Guess" is a string, but the program has to decide whether it equals the randomly generated number. I tried implementing a ConvertToInt32 statement but it did nothing. Can anybody help me with this?

    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                int number;
                string numberstring;
                string guess;
                Random rand;
                rand = new Random();
    
                number = rand.Next(1, 3);
    
            Start:
                do
                {
                    Console.WriteLine("Guess the number from 1 to 3.");
                    guess = Console.ReadLine();
    
                    if (guess = number)
                    {
                        Console.WriteLine("You've won.");
                    }
    
                    else
                    {
                        Console.WriteLine("Sorry, guess again.");
                        goto Start;
                    }
                } while (guess != "Q");
            }
        }
    }
    Last edited by Krunchyman; December 7th, 2011 at 09:34 AM.

  2. #2
    Join Date
    Dec 2008
    Posts
    144

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

    Couple of things.

    First, you need to change if (guess = number)- at this moment you're trying to assign the value of number to guess. To test equality you have to use 2 equal signs, like this:
    Code:
    if (guess == number)
    Now you can cast guess as an int. Use the int.TryParse method if casting doesn't work. It works like this:
    Code:
    int guess
    int.TryParse(Console.ReadLine(), out guess);
    HTH
    Code:
    if (Issue.Resolved)
    {
         ThreadTools.Click();
         MarkThreadResolved();
    }

  3. #3
    Join Date
    Jun 2011
    Posts
    33

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

    So, it should look like this?

    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                int number;
                int guess;
                int.TryParse(Console.ReadLine, out guess);
                Random rand;
                rand = new Random();
    
                number = rand.Next(1, 3);
    
            Start:
                do
                {
                    Console.WriteLine("Guess the number from 1 to 3.");
                    guess = Console.ReadLine();
    
                    if (guess == number)
                    {
                        Console.WriteLine("You've won.");
                    }
    
                    else
                    {
                        Console.WriteLine("Sorry, guess again.");
                        goto Start;
                    }
                } while (guess != "Q");
            }
        }
    }

  4. #4
    Join Date
    Jul 2005
    Location
    Louisville, KY
    Posts
    201

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

    Why are you using the goto? This isn't basic. remove them. Your code should work fine.

  5. #5
    Join Date
    Jun 2011
    Posts
    33

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

    I entered in the TryParse statement and ran the program. Apparently, it didn't fix the problem. I got the same error. Here's the code.

    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                int number;
                int guess;
                int.TryParse(Console.ReadLine(), out guess);
                Random rand;
                rand = new Random();
    
                number = rand.Next(1, 90004);
                do
                {
                    Console.WriteLine("Guess the number from 1 to 90004.");
                    guess = Console.ReadLine();
    
                    if (guess == number)
                    {
                        Console.WriteLine("You've won.");
                    }
    
                    else
                    {
                        Console.WriteLine("Sorry, guess again.");
                        goto Start;
                    }
                } while (guess != number);
            }
        }
    }

  6. #6
    Join Date
    Jan 2010
    Posts
    1,099

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

    First, remove "goto Start;" - no need for that at all.

    Second, tell us:
    (1) Is this an exception or a compiler error? If it's an exception, what is the type of the exception?
    (2) What is the exact error message?
    (3) At what line of that code it occurs?

    Make sure you post the exact code you're currently using, the one that produces the error.

    This line
    while (guess != "Q");
    could have caused it, but you've replaced it in the code sample you posted last.
    As far as I can tell, if you copied the code you pasted here (from your last post) into VS, it would work just fine (except for the goto).

    Could be that you forgot to change the type of one of your variables, or something. Read the error message carefully, double click it to be taken to the problematic line, see if there are any strings that are being used together with integers.

  7. #7
    Join Date
    Feb 2008
    Posts
    65

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

    The guess string must be converted to an int before the comparison takes place.
    Here are a few hints:
    Code:
                    guess_str = Console.ReadLine();
                    guess_str = guess_str.ToUpper();
                    if (guess_str != "Q")
                    {
                        guess_number = Convert.ToInt16(guess_str);
    Developing using:
    .NET3.5 / VS 2008

  8. #8
    Join Date
    Feb 2011
    Location
    United States
    Posts
    1,005

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

    Some background reading on why goto is no longer used: http://www.u.arizona.edu/~rubinson/c...d_Harmful.html
    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.

  9. #9
    Join Date
    Feb 2008
    Posts
    65

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

    BioPhysEngr, I agree that using "goto" is a bad practice. But why do modern languages, including C#, allow its usage? It is an unnecessary statement so it shouldn't be included in the language.
    Developing using:
    .NET3.5 / VS 2008

  10. #10
    Join Date
    Dec 2011
    Posts
    61

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

    goto is useful when you want to jump out of nested loops. Used properly, it can make code clean. But its side effects outwin its usefulness.

  11. #11
    Join Date
    Feb 2011
    Location
    United States
    Posts
    1,005

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

    Quote Originally Posted by Silent Sojourner View Post
    goto is useful when you want to jump out of nested loops. Used properly, it can make code clean. But its side effects outwin its usefulness.
    I don't think I agree. I would always recommend against the use of goto. If I had to jump out of a nested loop I'd either:

    (a) write a subroutine that could abort the loop using a return statement or
    (b) use a bool that must be set to true to continue loop execution. The interior loop can set it to false to abort the loop and allow the loop to end naturally.
    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.

  12. #12
    Join Date
    Jun 2011
    Posts
    33

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

    Quote Originally Posted by BioPhysEngr View Post
    I don't think I agree. I would always recommend against the use of goto. If I had to jump out of a nested loop I'd either:

    (a) write a subroutine that could abort the loop using a return statement or
    (b) use a bool that must be set to true to continue loop execution. The interior loop can set it to false to abort the loop and allow the loop to end naturally.
    I know the goto label is bad. I'll remove it and add a subroutine but first I kind of want to work on the problem at hand before I do anything else.


    Quote Originally Posted by TheGreatCthulhu View Post
    First, remove "goto Start;" - no need for that at all.

    Second, tell us:
    (1) Is this an exception or a compiler error? If it's an exception, what is the type of the exception?
    (2) What is the exact error message?
    (3) At what line of that code it occurs?

    Make sure you post the exact code you're currently using, the one that produces the error.

    This line
    while (guess != "Q");
    could have caused it, but you've replaced it in the code sample you posted last.
    As far as I can tell, if you copied the code you pasted here (from your last post) into VS, it would work just fine (except for the goto).

    Could be that you forgot to change the type of one of your variables, or something. Read the error message carefully, double click it to be taken to the problematic line, see if there are any strings that are being used together with integers.
    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.

  13. #13
    Join Date
    Feb 2008
    Posts
    65

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

    You have guess defined as an int, but Console.ReadLine() returns a string. That is the mismatch. That's why I gave you this line:
    string guess_str = Console.ReadLine();
    Then you can convert it to an integer using the statement:
    guess_number = Convert.ToInt16(guess_str);
    After you checked that the string is valid as a number, and not "Q".
    Developing using:
    .NET3.5 / VS 2008

  14. #14
    Join Date
    Feb 2011
    Location
    United States
    Posts
    1,005

    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 09: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.

  15. #15
    Join Date
    Feb 2011
    Location
    United States
    Posts
    1,005

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

    Quote Originally Posted by Jim_Auricman View Post
    guess_number = Convert.ToInt16(guess_str);
    Nitpick: This will convert guess_str to a short (which will then be automatically upcasted to an int). The preferred syntax when assigning an int is Convert.ToInt32(guess_str);. Actually, I like Int32.Parse(guess_str) most of all.
    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.

Page 1 of 2 12 LastLast

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
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center