c# filtering user input

sirch2

Joined Jan 21, 2013
1,037
A regex can only be applied to a string but you don't need to do both convert.toSingle and the regex, Convert.ToSingle will throw an exception if the user enters an invalid value. If you want to avoid the exception then you could read the user input into a String, do the regex check and then Convert.ToSingle.

But I would just do the convert, catch the exception and notify the user in the catch block.
 

djsfantasi

Joined Apr 11, 2010
9,163
Catching the exception is all well and good, but the entered value may not match a currency pattern. 1.234 would be seen as valid.

I'd follow your other example: input a string, validate against a regex, then convert to float/single.
 

Thread Starter

Dritech

Joined Sep 21, 2011
901
Hi again. I am trying to generate a random string and found the code below:

var chars ="abcdefghijklmnopqrstuvwxyz";
var stringChars =newchar[8];
var random =newRandom();

for(int i =0; i < stringChars.Length; i++)
{
stringChars= chars[random.Next(chars.Length)];
}
var finalString =newString(stringChars);

The problem is that although the string is created randomly, every time I call this method, the same random string is being generated.
Is there a way to generate a random string every time I call this method?
 

vpoko

Joined Jan 5, 2012
267
Thanks.

The problem is that it is not letting me compare the float data type.

This is how in am doing it:

The user is asked to enter a float (ex: 123.12)

I am reading the user input as follows: test = Convert.ToSingle(Console.ReadLine());
(where test is a variable of float data type)
Don't read user input into any data type other than a String. Instead, read it into a String, validate it (regex is your best bet, but you could use float.TryParse() for very rudimentary validation), and only then save it into a numeric type.

Another option would be to read it directly into a numeric type and catch the thrown exception if the user enters something invalid, but using exceptions as part of normal program flow is considered a bad idea.
 

vpoko

Joined Jan 5, 2012
267
Hi again. I am trying to generate a random string and found the code below:

var chars ="abcdefghijklmnopqrstuvwxyz";
var stringChars =newchar[8];
var random =newRandom();

for(int i =0; i < stringChars.Length; i++)
{
stringChars= chars[random.Next(chars.Length)];
}
var finalString =newString(stringChars);

The problem is that although the string is created randomly, every time I call this method, the same random string is being generated.
Is there a way to generate a random string every time I call this method?
I have no idea how newRandom is defined (or why you're using var for everything), but this is how you should initialize your Random variable using the clock as a seed (which will give you different values each time).

Random random = new Random();
 
Top