MFC Visual C++ code to check for valid number entries - c#

I have this MFC app with the following piece of code to check for the validity of numbers entered using a edit control in the app. Its validated as a string of chars.
bool invalid = FALSE;
int string_length = InputEdit.GetWindowText(text, 10);
if (text[0] == '-1')
for(i=1; i<string_length; i++)
if((text[i] < '0' || text[i] > '9' ) && text[i] != '.'){
MessageBeep(MB_ICONEXCLAMATION);
Reactive_Const_Status_Text.SetWindowText("Invalid AA Value");
invalid = TRUE;
}
else
for(i=0; i<string_length; i++)
if((text[i] < '0' || text[i] > '9' ) && text[i] != '.'){
MessageBeep(MB_ICONEXCLAMATION);
Reactive_Const_Status_Text.SetWindowText("Invalid AA Value");
invalid = TRUE;
}
if(!invalid){
double temp_value = atof(text);
reac.VelAA = temp_value;
}
So this edit control allows users to enter negative numbers. However can someone please shed some light about what this line "if (text[0] == '-1')" does in the code ? Is it checking for negative numbers and if so why does it use '-1' ? Secondly, I'm wanting to convert this code to C# and so how can I convert this line ?
Thanks in advance

Actually, this code is also checking for negative numbers. The first for loop checks from second digit onwards.
The line if (text[0] == '-1') is supposed to be if (text[0] == '-')
I guessed it this way because in C++ single quotes can be used only for single character and not for a string with more than one character.
In C# the same line if (text[0] == '-') will work.
Thanks.

Related

How do I check that even positions of a string array have only numbers?

I am learning my first ever programming language - which is C#.
I am making my first project in my apprenticeship which is teaching me C#. It is to produce a basic calculator.
The basic calculator takes a string input and provides a result. For example, input: "5 + 5". The answer will be 10 in a decimal format.
However, part of my validation is make the even indexes of the string array only be numbers, whilst the odd indexes of the string array can only be operators of "+", "-", "*", "/". How would I do this?
I have tried to do it here but I am struggling:
for (int index = 0; index <= calculatorInput.Length; index++)
{
if (index % 2 == 0)
{
if (Decimal.TryParse(calculatorInput[index]))
{
throw new CalculatorException("Even indexes must contain a number");
}
//check for number
}
else if (//code here)
{
throw new CalculatorException("Odd indexes must contain an operator");
//check for operator
}
}
Sorry if this question is too simple, but I would greatly appreciate the help!
My apologies for the late response. The comment from Rufus L (https://stackoverflow.com/users/2052655/rufus-l) helped to provide the solution I needed at the time.
decimal temp; if (decimal.TryParse(calculatorInput[index].ToString(), out temp)){} The TryParse method takes a string and an out parameter, which you are missing. But there are better ways to do what you want. – Rufus L Nov 1 '19 at 18:58
All answers and comments were very helpful in my development however. The calculator has been finished now though there is always room for improvement.
You can focus on operators for validation. They must always be somewhere inside the input string. Minus operator is an exception here if your calculator accepts negative numbers. But if the calculator is basic and does not support negative numbers, So the code below should be enough for operator validation:
string inputString = "10 + 10";
int index = inputString.IndexOf('+');
if ((index > -1) && ((index == 0) || (index ==inputString.Length-1)))
throw new CalculatorException("YOUR ERROR MESSAGE");
index = inputString.IndexOf('*');
if ((index > -1) && ((index == 0) || (index ==inputString.Length-1)))
throw new CalculatorException("YOUR ERROR MESSAGE");
index = inputString.IndexOf('/');
if ((index > -1) && ((index == 0) || (index ==inputString.Length-1)))
throw new CalculatorException("YOUR ERROR MESSAGE");
index = inputString.IndexOf('-');
if ((index > -1) && ((index == 0) || (index ==inputString.Length-1)))
throw new CalculatorException("YOUR ERROR MESSAGE");
///Calculation code
To increase readability I did not create a nested if-else statement.
After this code block, you can place your calculation code. I think it is enough for a new learner.

Substrings and Char.Is/Number Confusion. [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm a beginner at c# and how could I write a code that will check if:
the first 3 characters are letters
the next 3 are numbers,
next two letters
And the last character a number.
And if it is isn't write an error message.
I've tried using Substring(0,3) and putting it against Char.IsLetter just to attempt but failed.
Here's a correct way to do it using char.IsLetter and char.IsNumber.
if(myString.Length == 9
&& char.IsLetter(myString[0])
&& char.IsLetter(myString[1])
&& char.IsLetter(myString[2])
&& char.IsNumber(myString[3])
&& char.IsNumber(myString[4])
&& char.IsNumber(myString[5])
&& char.IsLetter(myString[6])
&& char.IsLetter(myString[7])
&& char.IsNumber(myString[8]))
{
// match.
}
Basically you have validate the length of the string, and then validate each character.
You could also use char.IsDigit to limit the match to radix-10 digit versus char.IsNumber that will match any Unicode character that is deemed a number (fractions, subscripts, superscripts, Roman numerals, currency numerators, encircled numbers, and script-specific digits). Also char.IsLetter will also match any Unicode character that is deemed a letter which will stray outside of the basic A-Z. To restrict numbers to 0-9 and letters to A-Z you could do this instead.
public static IsAtoZ(char c)
{
return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
}
if(myString.Length == 9
&& IsAtoZ(myString[0])
&& IsAtoZ(myString[1])
&& IsAtoZ(myString[2])
&& char.IsDigit(myString[3])
&& char.IsDigit(myString[4])
&& char.IsDigit(myString[5])
&& IsAtoZ(myString[6])
&& IsAtoZ(myString[7])
&& char.IsDigit(myString[8]))
{
// match.
}
But honestly at this point a regular expression will be more terse. But note that you'll still have to consider if you want to match Unicode characters and use the correct regular expression based on that.
you can use a regex
bool isMatch= Regex.IsMatch("abc123de4", #"\p{L}{3}\d{3}\p{L}{2}\d");
You could just use a regular expression:
var regex = new Regex("^[a-z]{3}[0-9]{2}[a-z]{2}[0-9]{1}$", RegexOptions.IgnoreCase);
var matces = regex.Matches(input);
where input is the string you want to check.
When we pass the option RegexOptions.IgnoreCase to the constructor of the Regex, we say that it doesn't matter if the letters are capital or not.
You could avoid to specify this parameter and state explicitly that you want both capital and small letters, as Rahul has correctly pointed out in his comment. This is done like below:
var regex = new Regex("^[a-z][A-Z]{3}[0-9]{2}[a-z][A-Z]{2}[0-9]{1}$");
var matces = regex.Matches(input);
You can access the individual characters of a string in C# like this:
string s = "1test";
char c = s[0];
c will be '1' one then.
In the next step you can use the Char.IsNumber Method which returns a bool. Just like this:
if(c.IsNumber()){}
Then you do the same thing for the next two chars except that you use the Char.IsLetter method.
I think there are several elegant ways to do this. Since you said that you're a beginner to C#, I would suggest just finding the easiest (most pseudo-code-like, IMHO) way to just express the problem/solution:
private bool MatchesPattern(string test)
{
// can't possibly match the pattern with less than 9 chars
if (test.Length < 9) return false;
int idx = 0;
// test are letters
for (int steps = 1; steps <= 3; steps++)
{
if (!char.IsLetter(test[idx++])) return false;
}
// test are numbers
for (int steps = 1; steps <= 3; steps++)
{
if (!char.IsNumber(test[idx++])) return false;
}
// test are letters
for (int steps = 1; steps <= 2; steps++)
{
if (!char.IsLetter(test[idx++])) return false;
}
// test last char is number
if (!char.IsNumber(test.Last())) return false;
return true;
}
You can test the results:
private void Test(string testValue)
{
if (!MatchesPattern(testValue))
{
Console.WriteLine("Error!");
}
}

How to test if an input value = char A - Z in C#

while (asteriskWord != hangCharacters && score < 5)
{
while ( letter != ) //This is where I want to test for A-Z a-z
{
Console.WriteLine("Enter a letter please");
letter = Convert.ToChar(Console.ReadLine());
}
}
After the first while-loop I want to be able to place the input inside of a while loop that breaks if the value is = letters A-Z or a-z.
This is so that if the user enters the wrong information, the loop will continue to ask for the information.
Thank you for your time and consideration. Also I tried doing letter != 'A' && letter != 'a'...... and so on, but it didn't work for some reason.
Characters can be compared to each other, just like numbers:
while (!((letter >= 'A' && letter <= 'Z') || (letter >= 'a' && letter <= 'z'))) {
Console.WriteLine("Enter a letter please");
letter = Convert.ToChar(Console.ReadLine());
}
Well the simplest way would be to just use comparisons. If you definitely want to do it in a single expression, Glorfindel's answer is appropriate. However, all those brackets and the negation makes me nervous of the readability. I'd break it into a separate method:
while (!IsValidLetter(letter))
{
...
}
...
private static bool IsValidLetter(char letter)
{
return (letter >= 'a' && letter <= 'z') ||
(letter >= 'A' && letter <= 'Z');
}
Whichever you find more readable - the latter is easier to modify later, of course, if you end up with more complicated requirements.
Another option is to use a regular expression, like this:
while (!Regex.IsMatch(letter, "[a-zA-Z]"))
{
Console.WriteLine("Enter a letter please!");
letter = Console.ReadLine();
}

How to search for number in string with method Contains and Linq in c#?

I create calculator which have buttons with numbers and operators for basic operation (+, -,...) and just want to filter buttons with numbers to detect when is clicked number (between 0-9). Also i put new eventhadler which convert sender to button.
I wondering what will be nice and easy way to filter the buttons with numbers (using linq)
What did i try so far is
if(btn.Text == btn.Text.Contains(x => x >= '0' && x <= '9'))
MessageBox.Show("number " + btn.Text + " is pressed!");
How to make upper code workable?
Here you go, for your immediate needs:
if(btn.Text.All(char.IsDigit))
{
//Do your stuff
}
If all you want to know is that is it a number or not do this. No LINQ is required
LINQ Way to check the numbers are between 0 and 9
if(yourstring.ToCharArray().Where(c=> c < '0' || c > '9').Any())
return false;
else
return true;
To check that it contains a valid number
double num;
if (double.TryParse(btn.Text, out num))
{
// It's a number!
}
or to check less than 10 without linq
static bool IsLessThanTen(string str)
{
foreach (char c in str)
{
if (c < '0' || c > '9')
return false;
}
return true;
}
if you need to check at least one number in the button text, then use below
return btn.Text.Any(char.IsDigit)
If you writing calculator, you better check NCalc - Mathematical Expressions Evaluator for .NET and this CodeProject tutorial
This should work
bool hasNumeric = yourString.IndexOfAny("0123456789".ToCharArray()) > -1;

Input string was not in correct form

Im really bad with c# i have only really the basic knowladge of c# i have this piece of code but i cant get it to work probelly debugger says the problem is here http://puu.sh/2h2wV the code is here this is im sorry this is probally such an easy mistake
i had other code true,was my old programm :(
Console.WriteLine("Sisesta esimene arv vahemikus 10-20");
vastus1 = int.Parse(Console.ReadLine());
Console.WriteLine("sisesta teine arv vahemikus 20-32");
vastus2 = int.Parse(Console.ReadLine());
Console.WriteLine("Vastus {0}", vastus2 - vastus1);
string tekst1 = Console.ReadLine();
vastus3 = int.Parse(tekst1); <------ debugger says problem is here
}
while ((vastus1 < 1 || vastus2 < 12));
if (vastus3 >= 3 && vastus3 >= 5)
{
Console.WriteLine("On Kevad");
{
if (vastus3 >= 6 && vastus3 >= 8)
{
Console.WriteLine("on suvi");
}
}
if (vastus3 >= 9 && vastus3 >= 11)
{
Console.WriteLine("on sügis");
}
if (vastus3 >= 11 && vastus3 >= 2)
{
Console.WriteLine("on talv");
}
}
}
}
}
Well the error says it all really
The input string was not in the right format
In the context of what you're doing, this means that whatever you've typed into the console which you're passing directly to int.Parse cannot be parsed as an int.
If you expect that sometimes what is typed in to the console to not be numeric you could use int.TryParse to ascertain whether it is valid.
int vastus3 = 0;
while(!int.TryParse(Console.ReadLine(),out vastus3 ))
{
Console.WriteLine("Invalid number, try again!");
}
// here "vastus3" will have your integer
This can go into your code exactly where your current line which fails is.
Jamiec's explanation is correct. If the integers you are looking for always occur in the same format at the end of the string you could use Substring to get the specific characters then do your comparison checks.
Here is an example on how to remove characters from the end of a string using Substring.
Substring a string from the end of the string
And the msdn
http://msdn.microsoft.com/en-us/library/system.string.substring%28v=vs.71%29.aspx

Categories

Resources