Integer to boolean convertion

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Denden
    New Member
    • Aug 2014
    • 33

    Integer to boolean convertion

    Good evening, ive written a simple code but throws an error in C#, why is this happen.
    Code:
    	bool inputValue = Convert.ToBoolean(Console.ReadLine());
    		Console.WriteLine(inputvalue);
    		Console.ReadLine();
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    You know it's pretty hard to help you fix an error if you don't actually tell us what error you are getting.

    I am going to assume that the error is thrown on the first line of the code you posted as it tries to convert whatever the user typed into a Boolean...but if the user typed something like "Denden" it is obviously not going to work.

    -Frinny

    Comment

    • Denden
      New Member
      • Aug 2014
      • 33

      #3
      um, i tried to input 1 and expecting that the compiler will give me a false value but give me an error instead.

      System.FormatEx ception: String was not recognized as a valid Boolean.
      at System.Boolean. Parse(String value)
      at System.Convert. ToBoolean(Strin g value)

      Comment

      • Frinavale
        Recognized Expert Expert
        • Oct 2006
        • 9749

        #4
        Values gathered from the command line read are strings.


        Try using the Boolean.TryPars e method to convert attempt to convert the string into a Boolean instead of directly converting like you are.

        For example:
        Code:
        string inputValue = Console.ReadLine();
        bool flag;
        
        if (Boolean.TryParse(value, out flag))
        {
          Console.WriteLine("You provided a valid Boolean value: '{0}'", flag);
        }else{
          Console.WriteLine("The value '{0}' cannot be converted into true or false", inputValue);
        }
        You could do your own thing to validate the information the user provided and then create a Boolean.

        For example if my application asked you "Do you like this website? (yes or no)" I would take what the user provided and create my Boolean accordingly.

        Like this for example:
        Code:
        string inputValue = Console.ReadLine();
        bool theResult;
        
        if(String.Compare(inputValue,"yes",true) == 0)
        {
         theResult = true; 
        }else if (String.Compare(inputValue,"no",true) == 0)){
           theResult = false;
        }else{
          Console.WriteLine("You did not answer the question correctly");
        }

        Comment

        Working...