C# noob with a little problem here

  • Context: C# 
  • Thread starter Thread starter stonecoldgen
  • Start date Start date
  • Tags Tags
    Noob
Click For Summary
SUMMARY

The discussion centers on a common issue faced by beginners in C# programming, specifically regarding the handling of user input. The user initially attempts to read an integer using Console.Read(), which captures the ASCII value of the key pressed instead of the actual integer input. The correct approach is to utilize Console.ReadLine() followed by Int32.Parse() to properly convert the input string to an integer. This solution effectively resolves the problem of incorrect boolean evaluation in the conditional statement.

PREREQUISITES
  • Basic understanding of C# programming syntax
  • Familiarity with data types and type conversion in C#
  • Knowledge of console input/output methods in C#
  • Understanding of conditional statements in programming
NEXT STEPS
  • Explore C# Console.ReadLine() for reading user input as strings
  • Learn about data type conversion in C# using methods like Int32.Parse()
  • Investigate error handling in C# to manage invalid user input
  • Study conditional logic and boolean expressions in C#
USEFUL FOR

Beginner C# developers, programming students, and anyone troubleshooting input handling in console applications.

stonecoldgen
Messages
108
Reaction score
0
Hi, so I have this code:


Code:
namespace Program1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Is the numer less than 10?");

      

            int numero = Console.Read();

            if (numero < 10)
            {
                Console.WriteLine("true");
            }
            else
            {
                Console.WriteLine("false");
            }

           

        }
    }
}




The console is always writing the line "false" even if I input a number that should return "true."


any idea what am I doing wrong?
 
Technology news on Phys.org
maybe you have to cast the input into an integer as it comes in, else it converts to integer zero
 
Console.Read returns the ascii code for the key pressed, not the number itself.

Try this:
Code:
            int numero = Int32.Parse(Console.ReadLine());
 

Similar threads

  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 10 ·
Replies
10
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 18 ·
Replies
18
Views
2K
  • · Replies 15 ·
Replies
15
Views
4K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 13 ·
Replies
13
Views
5K
Replies
8
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 2 ·
Replies
2
Views
1K