C++ Windows Form - If statements - c++

I'm trying to make a password strength checker, at the moment i've got it setup so that if 'password' is typed into the password field then the strength goes red, and that if you type anything else it goes green
I've done this using the following if statement:
try{
if (password_textbox_form3->Text == "password")
{
strength_color_textbox->BackColor = Color::Red;
}
else
{
strength_color_textbox->BackColor = Color::Green;
}
}
catch (Exception^ )
{
strength_color_textbox->BackColor = Color::Black;
}
What i'm trying to do now and what i'm stuck on, is how to create a field called passwordscore that goes through a list of if statements and adds 10 if for example the password they have entered has more than 8 chars, and then from this score I can change the color of the strength box (red to green) that way
String ^ strength = password_textbox_form3->Text; //makes whatever the user enters in pw tb now called string
int passwordscore=0;
while // some sort of while loop to increment passwordscore? //passwordscore=passwordscore+1;
try{
if (strength //contains more than 8 characters)
{
//passwordscore +10
}
if (strength //contains a special character !"£$%^&*)
{
//password score +10
}
if (passwordscore <=10)
{
strength_color_textbox->BackColor = Color::Red;
}
if (passwordscore <=20)
{
strength_colour_textbox->BackColor = Color::Green;
}
I've started by assigning the contents of the password textbox to a string called strength (i think) and then got stuck on the IF statements such as how to see if strength has more than 8 characters etc
Any help or direction is appreciated, thanks
EDIT - found this from MSDN but I think it's in C#, can't be that much different to what i'm trying to do?
String ^ strength = password_textbox_form3->Text;
int numberOfDigits = 0;
int numberOfLetters = 0;
int numberOfSymbols = 0;
foreach (char c in strength)
{
if (char.IsDigit(c))
{
numberOfDigits++;
}
else if (char.IsLetter(c))
{
numberOfLetters++;
}
else if(char.IsSymbol(c))
{
numberOfSymbols++;
}
}

Take in the password as characters, and count the number of characters in the password form so that if the number of characters is >= 8 you can set the strength points to ten. Additionally you can use strings and put individual characters into a vector, and use the vector's index to count the # of characters.
EDIT TO FIRST EDIT:
Just to explain the new code posted:
A character can be either a alphabetical character (a,b,c) a number(1,2,3) or a symbol(+*^) obviously.
In the code they use one general FOREACH statement to contain three other if statements in which the character is checked to see if it is an alphabetical char a num or a symbol using the std library functions IsDigit IsSymbol IsLetter.
It adds one to the appropriate, initially declared variables whenever a character qualifies as one of the three categories.
For your purpose, you could use a similar technique but declare an int Pw_Str and Total_Char and add an if statement to increase Total_Char as necessary. When Total_Char exceeds 8 you can add 10 to Pw_Str as required and change the color using the Pw_Str variable.
To make any such code more compact instead of using if statements over and over i would suggest using a FOR loop to wind through each character and to add to the necessary variables.

Related

How do I use flag variables to produce output for a program designed to search an array for a string provided via user input?

I'm working on an ungraded practice assignment and am struggling with the C++ code required. The assignment parameters are to write a program which takes a string provided by user input, searches an array containing 10 elements, and sets the value of a flag variable depending on whether or not user input matches a string contained within the array. The program then outputs a phrase if the string was not found, as determined by referencing the value of the flag variable.
I have the following code so far:
// MichiganCities.cpp - This program prints a message for invalid cities in Michigan.
// Input: Interactive
// Output: Error message or nothing
#include <iostream>
#include <string>
using namespace std;
int main()
{
// Declare variables
string inCity; // name of city to look up in array
const int NUM_CITIES = 10;
// Initialized array of cities
string citiesInMichigan[] = {"Acme", "Albion", "Detroit", "Watervliet", "Coloma", "Saginaw", "Richland", "Glenn", "Midland", "Brooklyn"};
bool foundIt = false; // Flag variable
int x; // Loop control variable
// Get user input
cout << "Enter name of city: ";
cin >> inCity;
// Write your loop here
for(x=0; x<NUM_CITIES; x++){
// Write your test statement here to see if there is
// a match. Set the flag to true if city is found.
if(citiesInMichigan[x] == inCity)[
set foundIt = true,;
break;
]
}
// Test to see if city was not found to determine if
// "Not a city in Michigan" message should be printed.
if(foundIt == false){
cout << "City not in Michigan.";
return 0;
}
} // End of main()
I'm fairly certain what I've got here should do what I'm trying to do, but I get syntax errors requesting brackets [] in odd places and I'm lost on what I'm doing wrong.
I'm not looking for someone to provide correct code for me to simply copy, as I'm trying to learn. I'm looking for someone who can explain what I've done wrong, what rules I'm breaking, and/or what steps I can take to get this code working.
You have the right idea, but have a couple of syntactic mistakes.
First, blocks in C++ (and many other languages), are denoted by curly braces ({ and }), not square brackets like you have in your condition.
Second, setting a value to a variable is done by the assignment operator, = (i.e., somevariable = somevalue). There is no "set" keyword in C++.
To put those two points together, the condition inside the loop should look like this:
if (citiesInMichigan[x] == inCity) {
foundIt = true;
break;
}

Edit string by calling it using concatenation in C++

I'm a very new C++ user (and a new StackOverflow user at that), and I'm trying to code a very basic Tic-Tac-Toe (Naughts and Crosses) game. I'm not sure how to render the board as it is updated.
My main question is if it is possible to call a string using concatenation. I have an array set up that indexes the states of the 9 spaces of the board using a 0 for empty, a 1 for an X, and a 2 for an O. If I set up 9 variables in a user-defined renderBoard() function named bit1, bit2, etc; Can I call them this way:
void renderBoard()
{
int i = 1;
string bit1;
string bit2;
string bit3;
string bit4;
string bit5;
string bit6;
string bit7;
string bit8;
string bit9;
while (i < 10)
{
if (Spaces[i] = 0)
{
(bit + i) = * //This is the main bit I'm wondering about
}
else
{
//Check for 1, 2, and edit the string bits accordingly
}
++i;
}
//Put all of the strings together, as well as some more strings for adding the grid
//Output the whole concatenated string to the command line
}
If anyone knows of a better way to do this, please let me know. I've tried Googling and rifling through various C++ help websites, but I find it difficult to express my particular case through anything other than a long-winded and specific explanation.
Thanks for you help!!
If I correctly understood your problem, your problem is that you want to access the strings named bit1, bit2, etc using a variable i like bit + i.
And no, you cannot do that!
It will throw a compile time error.
Please correct me if I didn't get what you are looking for.
But one question is still in my mind that why are you using string variables bit1, bit2 etc?
I think you just want to store single digit value in those strings. If this is the case, you can just use a single string of length 9.
You can do this as follows:
int i = 0; //because string indices start from 0 and also array indices.
string bit(9, ' '); //declare a string of length 9 with default value of a space (you can modify it with your default value)
while (i < 9) { // i < 9 because highest index will be 8
if (Spaces[i] == 0) {
bit[i] = '*';
} else {
}
++i;
}
Declaring 9 variables like this is apparently wrong. What you are looking for is an array.
std::array<std::string, 9> bits;
(You need #include <array> and #include <string>.)
Then, you can traverse the string using a for-loop: (in C++, arrays are indexed starting from zero, not one)
for (std::size_t i = 0; i < 9; ++i) {
// operate on bits[i]
}
In the for-loop, you can use the subscript operator to access the element: bits[i].
Finally, to put all the strings together, use std::accumulate:
std::accumulate(bits.begin(), bits.end(), std::string{})
(You need #include <numeric>.)

How to input a multi-digit integer into an Arduino using a 4x4 keypad?

I am trying to make a combination lock using an Arduino, a keypad and a Servo but I have come across an obstacle.
I can't find a way to store a 4 digit value in a variable. since keypad.getKey only allows to store one digit.
After some browsing on the internet I came upon a solution for my problem on a forum but the answer didn't include a code sample, and I couldn't find anything else about in on the internet.
The answer said to either use a time limit for the user to input the number or a terminating character (which would be the better option according to them).
I would like to know more bout these terminating characters and how to implement them, or if anybody could suggest a better solution that would be much appreciated as well.
Thank you in advance,
To store 4 digit values, the easiest and naive way to do it is probably to use an array of size 4. Assuming keypad.getKey returns an int, you could do something like this: int input[4] = {0};.
You will need a cursor variable to know into which slot of the array you need to write when the next key is pressed so you can do some kind of loop like this:
int input[4] = {0};
for (unsigned cursor = 0; cursor < 4; ++cursor) {
input[cursor] = keypad.getKey();
}
If you want to use a terminating character (lets say your keyboard have 0-9 and A-F keys, we could say the F is the terminating key), the code changes for something like:
bool checkPassword() {
static const int expected[4] = {4,8,6,7}; // our password
int input[4] = {0};
// Get the next 4 key presses
for (unsigned cursor = 0; cursor < 4; ++cursor) {
int key = keypad.getKey();
// if F is pressed too early, then it fails
if (key == 15) {
return false;
}
// store the keypress value in our input array
input[cursor] = key;
}
// If the key pressed here isn't F (terminating key), it fails
if (keypad.getKey() != 15)
return false;
// Check if input equals expected
for (unsigned i = 0; i < 4; ++i) {
// If it doesn't, it fails
if (expected[i] != input[i]) {
return false;
}
}
// If we manage to get here the password is right :)
return true;
}
Now you can use the checkPassword function in your main function like this:
int main() {
while (true) {
if (checkPassword())
//unlock the thing
}
return 0;
}
NB: Using a timer sounds possible too (and can be combined with the terminating character option, they are not exclusive). The way to do this is to set a timer to the duration of your choice and when it ends you reset the cursor variable to 0.
(I never programmed on arduino and don't know about its keypad library but the logic is here, its up to you now)
In comment OP says a single number is wanted. The typical algorithm is that for each digit entered you multiply an accumulator by 10 and add the digit entered. This assumes that the key entry is ASCII, hence subtracting '0' from it to get a digit 0..9 instead of '0'..'9'.
#define MAXVAL 9999
int value = 0; // the number accumulator
int keyval; // the key press
int isnum; // set if a digit was entered
do {
keyval = getkey(); // input the key
isnum = (keyval >= '0' && keyval <= '9'); // is it a digit?
if(isnum) { // if so...
value = value * 10 + keyval - '0'; // accumulate the input number
}
} while(isnum && value <= MAXVAL); // until not a digit
If you have a backspace key, you simply divide the accumulator value by 10.

How to build Jape rules in gate

I need to build a rule where Lhs check if the first character of word beggin in b then check the whole word without the first character that found in lookup
This is a sample code for something similar to what you want(Copied from https://gate.ac.uk/wiki/jape-repository/strings.html#section-1.). You can read a little more and get to the exact solution:
Rule:GetMobile
(
{Phone}
):tag
-->
:tag{
// get the offsets
Long phoneStart = tagAnnots.firstNode().getOffset();
Long phoneEnd = tagAnnots.lastNode().getOffset();
// check the number is longer than or equal to 2 characters (just in case)
if(phoneEnd - phoneStart >= 2) {
try {
String firstTwoChars = doc.getContent()
.getContent(tagAnnots.firstNode().getOffset(),
tagAnnots.firstNode().getOffset() + 2).toString();
// check it matches 07
if("07".equals(firstTwoChars)) {
// create the new annotation
gate.FeatureMap features = Factory.newFeatureMap();
features.put("kind", "mobile");
outputAS.add(tagAS.firstNode(),
tagAS.lastNode(), "Phone", features);
}
}
catch(InvalidOffsetException e) {
// not possible
throw new LuckyException("Invalid offset from annotation");
}
}
}
Here are some places where you can read up:
https://gate.ac.uk/wiki/jape-repository/
https://gate.ac.uk/sale/talks/gate-course-jun14/module-1-jape/module-1-jape.pdf

grabbing data sets from a file with an arbitrary amount of spaces

**No direct answers or code examples please, this is my homework which i need to learn from. I'm looking for help concerning the algorithm i need to develop.
I seem to be having a logic error in coming up with a solution for a portion of my class work, the program involves multiple files, but here is the only relevant portion:
I have a file PlayerStats that holds the stats for a basketball player in:
rebounds
points
assists
uniform #
my initial reaction would be to create a while loop and read these into a temporary struct that holds these values, then create a merge function that merges the values of the temp struct with the inital array of records, simple enough?
struct Baller
{
//other information on baller
int rebounds;
int assists;
int uniform;
int points;
void merge(Baller tmp); //merge the data with the array of records
}
//in my read function..
Baller tmp;
int j = 0;
inFile << tmp.uniform << tmp.assists << tmp.points << tmp.rebounds
while(inFile){
ArrayRecords[j].merge(tmp);
j++;
//read in from infile again
}
The catch:
The file can have an arbitrary number of spaces between the identifiers, and the information can be in any order(leaving out the uniform number, that is always first). e.g.
PlayerStats could be
11 p3 a12 r5 //uniform 11, 3 points 12 assists 5 rebounds
//other info
OR
11 p 3 r 5 a 12 //same exact values
What I've come up with
can't seem to think of an algorithm to grab these values from the file in the correct order, i was thinking of something along these lines:
inFile << tmp.uniform; //uniform is ALWAYS first
getline(inFile,str); //get the remaining line
int i = 0;
while(str[i] == " ") //keep going until i find something that isnt space
i++;
if(str[i] == 'p') //heres where i get stuck, how do i find that number now?
else if(str[i] == 'a')
eles if(str[i] = 'r'
If you're only going to check one letter, you could use a switch statement instead of if / else, that would make it easier to read.
You know where the number starts at that point, (hint: str[i+1]), so depending on what type your str[] is, you can either use atoi if its a char array, or std::stringstream if it's an std::string.
I'm tempted to give you some code, but you said not too. If you do want some, let me know and I'll edit the answer with some code.
Instead of using a 'merge' function, try using an std::vector so you can just push_back your structure instead of doing any 'merging'. Besides, your merge function is basically a copy assignment operator, which is created by the compiler by default (you don't need to create a 'merge' function), you just need to use = to copy the data across. If you wanted to do something special in your 'merge' function, then you should overload the copy assignment operator instead of a 'merge' function. Simples.
Do something like that:
int readNumber () {
while isdigit (nextchar) -> collect in numberstring or directly build number
return that number;
}
lineEater () {
Read line
skip over spaces
uniform=readNumber ();
haveNum=false;
haveWhat=false;
Loop until eol {
skip over spaces
if (isdigit)
number=readNumber ();
skip over spaces
haveNum=true;
else
char=nextChar;
haveWhat=true;
if (haveChar and haveNum) {
switch (char) {
case 'p' : points=number; break;
...
}
haveNum=false;
haveWhat=false;
}
}
or, if you are more ambitous, write a grammar for your input and use lex/yacc.