C
C#8mo ago
Raquel

how to I take int user input

what am i doing wrong it is saying that i cant take in the int because it is a string. What is the easiest way to to take int user input
No description
8 Replies
Jimmacle
Jimmacle8mo ago
$tryparse
MODiX
MODiX8mo ago
When you don't know if a string is actually a number when handling user input, use int.TryParse (or variants, e.g. double.TryParse)
if(int.TryParse("123", out int number))
{
var total = number + 1;
Console.WriteLine(total); // output: 124
}
if(int.TryParse("123", out int number))
{
var total = number + 1;
Console.WriteLine(total); // output: 124
}
TryParse returns a bool, where true indicates successful parsing. Remarks: - Avoid int.Parse if you do not know if the value parsed is definitely a number. - Avoid Convert.ToInt32 entirely, this is an older method and Parse should be preferred where you know the string can be parsed. Read more here
Denis
Denis8mo ago
Variables should be camel case, instead of upper camel case:
int numRed;
int numGreen;
int numBlue;
int numRed;
int numGreen;
int numBlue;
To properly handle user input, you'll probably have to use loops. When the user enters anything but a number, the parsing will fail. You'll want to display some error message to remind the user that you want a numeric value and ask for input again.
JohnWick
JohnWick8mo ago
Maybe NumRed = Convert.ToInt32(Console.ReadLine()); Try this
JohnWick
JohnWick8mo ago
So this error says, that you must convert string to int
No description
JohnWick
JohnWick8mo ago
So you must convert it Like this Understand?
Denis
Denis8mo ago
Please no. Literally says in the previous message not to use Convert It's a legacy method, do not use it. Period. If you wish to convert your number unsafely without checking whether the string is truly a number, use
int.Parse(....)
int.Parse(....)
Just read this. If you have additional questions, go ahead
Raquel
RaquelOP8mo ago
Thank you i will try this today Thank you
Want results from more Discord servers?
Add your server