C
C#2y ago
Spekulant

❔ ✅ Inputing numbers

I want to write a short code that gets random input. It reads two numbers between random inputs.
using System;
namespace hello_wolrd;
class Program
{
static void Main(string[] args)
{

int a = Inputer.ReadSymbol();
int b = Inputer.ReadSymbol();
Console.WriteLine(a + b);
}
}

class Inputer
{
public static int ReadSymbol()
{
int symbol = Console.Read();
while ((symbol < '0') || (symbol > 9))
symbol = Console.Read();
int x = 0;

while ((symbol >= '0') && (symbol <= '9'))
{
x = 10 * x + (symbol - '0');
symbol = Console.Read();
}


return x;
}
}
using System;
namespace hello_wolrd;
class Program
{
static void Main(string[] args)
{

int a = Inputer.ReadSymbol();
int b = Inputer.ReadSymbol();
Console.WriteLine(a + b);
}
}

class Inputer
{
public static int ReadSymbol()
{
int symbol = Console.Read();
while ((symbol < '0') || (symbol > 9))
symbol = Console.Read();
int x = 0;

while ((symbol >= '0') && (symbol <= '9'))
{
x = 10 * x + (symbol - '0');
symbol = Console.Read();
}


return x;
}
}
im somewhere around here.. but i havent figured the minus numbers also... the input can be something like:
115
aaa-12

a
115
aaa-12

a
22 Replies
Angius
Angius2y ago
Use int.TryParse() if you want to support negative numbers
Spekulant
Spekulant2y ago
could you explain more this is my first code in c#... i come from python xd also new to C languages
Angius
Angius2y ago
$tryparse
MODiX
MODiX2y ago
The TryParse pattern is considered best practice of parsing data from a string: - a TryParse method returns true or false to inform you if it succeeded or not, so you can use it directly in a condition, - since C# 7 you can declare a variable that will be used as an out argument inline in an argument list, - it forces you to check if the out argument contains valid data afterwards, Avoid: Convert.ToInt32 — it's a bad choice for parsing an int. It exists only for backwards compatibility reasons and should be considered last resort.
return Convert.ToInt32(null); //returns 0. null should not be considered as 0 ever
return Convert.ToInt32("asdf"); //throws FormatException
return Convert.ToInt32(null); //returns 0. null should not be considered as 0 ever
return Convert.ToInt32("asdf"); //throws FormatException
(Note: Convert does contain useful conversion methods: To/FromBase64String, To/FromHexString, ToString(X value, int toBase), ToX(string? value, int fromBase)) Avoid: int.Parse — you have to use a try/catch statement to handle invalid input, which is a less clean solution.
var number = int.Parse("abc"); //throws FormatException
var number = int.Parse(""); //throws FormatException
var number = int.Parse("abc"); //throws FormatException
var number = int.Parse(""); //throws FormatException
Use int.TryParse https://docs.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-5.0#System_Int32_TryParse_System_String_System_Int32__
if (int.TryParse(someInput, out var result))
{
Console.WriteLine($"Thanks for giving me the following number: {result}!");
}
else
{
Console.WriteLine("You didn't give me a valid number :c");
}
if (int.TryParse(someInput, out var result))
{
Console.WriteLine($"Thanks for giving me the following number: {result}!");
}
else
{
Console.WriteLine("You didn't give me a valid number :c");
}
Int32.TryParse Method (System)
Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the operation succeeded.
Spekulant
Spekulant2y ago
@Angius i though i should have another variable that checks if its minus sign and if the following chars are number then its negative would int.TryParse() work even on a str like: ag-123gago
Angius
Angius2y ago
No
MODiX
MODiX2y ago
Angius#1586
REPL Result: Success
if (int.TryParse("ag-123gago", out var result))
{
Console.WriteLine($"Thanks for giving me the following number: {result}!");
}
else
{
Console.WriteLine("You didn't give me a valid number :c");
}
if (int.TryParse("ag-123gago", out var result))
{
Console.WriteLine($"Thanks for giving me the following number: {result}!");
}
else
{
Console.WriteLine("You didn't give me a valid number :c");
}
Console Output
You didn't give me a valid number :c
You didn't give me a valid number :c
Compile: 610.725ms | Execution: 87.333ms | React with ❌ to remove this embed.
Spekulant
Spekulant2y ago
well i want my code to spit out -123 so should i still use int.TryParse
Angius
Angius2y ago
Ah, you want to pull out numbers from random gibberish? As in, you want usyadgfuyawi4rdsfjhg to give you 4?
Spekulant
Spekulant2y ago
yes i want to pull out 2 numbers from gibberish and sum them up but they can be like negative so i have to check if there is a minus sign before the number began
Angius
Angius2y ago
You could just try regex Or, sure, build some sort of a parser
var numbers = new List<int>();
var queue = new Queue(input);
while (queue.Count > 0)
{
var ch = queue.Dequeue();
if (ch.IsNumber)
{
numbers.Add(ch - '0');
}
else if (ch == '-')
{
var num = ch.Dequeue();
if (num.IsNumber)
{
numbers.Add((num - '0') * -1);
}
}
}
var numbers = new List<int>();
var queue = new Queue(input);
while (queue.Count > 0)
{
var ch = queue.Dequeue();
if (ch.IsNumber)
{
numbers.Add(ch - '0');
}
else if (ch == '-')
{
var num = ch.Dequeue();
if (num.IsNumber)
{
numbers.Add((num - '0') * -1);
}
}
}
something like that
Spekulant
Spekulant2y ago
dont know what regex is
Spekulant
Spekulant2y ago
using System;
namespace hello_wolrd;

class Inputer
{
public static int ReadSymbol()
{
int symbol = Console.Read();
int checker = '?';
while ((symbol < '0') || (symbol > '9'))
checker = symbol;
symbol = Console.Read();

int x = 0;

while ((symbol >= '0') && (symbol <= '9'))
{
x = 10 * x + (symbol - '0');
symbol = Console.Read();
}
if (checker == '-')
x = -x;

return x;
}
}

class Program
{
static void Main(string[] args)
{

int a = Inputer.ReadSymbol();
int b = Inputer.ReadSymbol();
Console.WriteLine(a + b);
}
}
using System;
namespace hello_wolrd;

class Inputer
{
public static int ReadSymbol()
{
int symbol = Console.Read();
int checker = '?';
while ((symbol < '0') || (symbol > '9'))
checker = symbol;
symbol = Console.Read();

int x = 0;

while ((symbol >= '0') && (symbol <= '9'))
{
x = 10 * x + (symbol - '0');
symbol = Console.Read();
}
if (checker == '-')
x = -x;

return x;
}
}

class Program
{
static void Main(string[] args)
{

int a = Inputer.ReadSymbol();
int b = Inputer.ReadSymbol();
Console.WriteLine(a + b);
}
}
i got this but when i input 1 and 2 in terminal it prints out 0
Angius
Angius2y ago
Angius
Angius2y ago
Remember that it's not Python What you have here is
while ((symbol < '0') || (symbol > '9'))
{
checker = symbol;
}
symbol = Console.Read();
while ((symbol < '0') || (symbol > '9'))
{
checker = symbol;
}
symbol = Console.Read();
not
while ((symbol < '0') || (symbol > '9'))
{
checker = symbol;
symbol = Console.Read();
}
while ((symbol < '0') || (symbol > '9'))
{
checker = symbol;
symbol = Console.Read();
}
Spekulant
Spekulant2y ago
okey thanks it works now can it be written more elegantly tho like the same thing but so much better and cleaner?like programs in python @Angius also if i have only integers also negative on input and i want to put it inside an array should i use the code that you pasted the regex one?
Angius
Angius2y ago
You can use regex, sure
Spekulant
Spekulant2y ago
dont know why you use queue tho
Angius
Angius2y ago
To make parsing easier Also, the code there is not regex
Spekulant
Spekulant2y ago
c# harder then cpp !close
Accord
Accord2y ago
Closed! Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.