/* I have written a code for a simple hangman based on instructions given, I just want to know how to detect the duplicated inputs. For this code, It only detects correct letters and the length
For example:
user input: HAM
H
A
A
HANGMAN! */
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
// Word to be guessed can be assumed to be at most 20 characters long (including end-of-string null character)
char HangmanWord[20];
// Variable to store current guess
char GuessLetter;
int count = 0;
std::cin >> HangmanWord;
//char guessedletter[strlen(HangmanWord)];
//int j = 0;
bool valid = true;
// Check that input word only consists of uppercase English letters
for (int i = 0; i < strlen(HangmanWord); i++)
{
if ((HangmanWord[i] > 'Z') || (HangmanWord[i] < 'A'))
{
valid = false;
break;
}
}
while (valid == true)
{
std::cin >> GuessLetter; //Takes the Guess letter
if ((GuessLetter > 'Z') || (GuessLetter < 'A')) //Check that guessed letter is uppercase
{
break;
}
else
{
for (int i = 0; i < strlen(HangmanWord); i++) //loop to check every letter in word
{
if (GuessLetter == HangmanWord[i]) { //if the letter is equal to any letter in the word the count increases
count++;
break;
}
if (i == strlen(HangmanWord) - 1) { //If no letter is equal to any letter in the word the program exits
valid = false;
}
}
if (count == strlen(HangmanWord)) { //Checks if all letters were guessed and exits the loop after
valid = false;
}
}
}
if (count == strlen(HangmanWord)) { //Checks if all letters were guessed correct to print Hangman
cout << "HANGMAN!\n";
valid = false;
}
If you want to detect whether a letter has already been input, you can work with ASCII characters being represented by numbers. Assuming we limit ourselves to uppercase letters, 'A' is 65 and 'Z' is 90.
We can do math with these. 'A' - 'A' is 0 and 'C' - 'A' is 2.
We also know that arrays are indexed starting from zero.
We can put these things together to create an array of boolean values, and flag them as letters are guessed.
std::array<std::bool, 26> already_guessed;
std::fill(already_guess.begin(), already_guessed.end(), false);
And we can then check on whether a letter has been guessed by looking it up. Consider, for instance, checking whether 'D' has been guessed. They should start out false, as nothing has been guessed at the beginning.
already_guessed['D' - 'A']
If it hasn't, we can mark it as guessed:
already_guessed['D' - 'A'] = true
Related
I'm new to learning functions, I'm basically doing an excercise for college where the user enters in two letters e.g a j and then letter one is higher than letter two in the alphabet and vice versa. It has to be a bool function here is the question.
4.
a. Write a prototype for a function IsAlphaHigher that can be passed a pair of
characters and that will return a Boolean value indicating whether or not the
first character is higher alphabetically. (Note āaā is higher than āzā)
b. Write a definition for the function IsAlphaHigher
c. Write a test application that will use the function IsAlphaHigher.
Now Its easy if the user enters something like a n ,or capital letter A N . Which ever letter is lowest on the ASCII table is higher on the alphabet. But what about when the user enters something like the letters uppercase R lowercase a for example,upper case R is 82 on the ASCII table and small a is 97.
I figured out that if any small case letter - any uppercase letter = greater than 32 then the upper case letter is higher on the alphabet.
The logic behind this is that a - A = 32 , b - B = 32 , q - Q = 32 etc. So anything above 32 the upper case letter is higher than the lower case, anything below 32, the lower case is higher than the uppercase letter.
I used a series of if statements to get around this however i'm getting an error and i'm not quite sure where its coming from or why so i'd really appreciate some help.
thanks.
#include <iostream>
using namespace std;
bool IsAlphaHigher(char letterOne, char letterTwo);
int main()
{
char letter1, letter2;
cout << "Enter two letters ";
cin >> letter1 >> letter2;
IsAlphaHigher(letter1, letter2);
if (IsAlphaHigher(letter1,letter2) == 1)
cout << "letter one is higher on the alphabet than letter two ";
else
cout << "letter two is higher on the alphabet than letter one ";
}
bool IsAlphaHigher(char letterOne, char letterTwo)
{
bool status;
if (letterOne < 90 && letterTwo < 90)
{
if (letterOne < letterTwo)
status = true;
else
status = false;
}
if (letterOne > 90 && letterTwo < 90)
{
if (letterOne < letterTwo)
status = true;
else
status = false;
}
if (letterOne < 90 && letterTwo > 90)
{
if (letterTwo - letterOne <= 32)
status = true;
else
status = false;
}
if (letterOne > 90 && letterTwo < 90)
{
if (letterOne - letterTwo <= 32)
status = true;
else
status = false;
}
return status;
}
When I build it, it says theres no errors but when I go into the command shell and type in two letters it gives me a "Run time check failure #3 T"
I have no idea why.
This is my first boolean function ever so I imagine i'm doing something wrong, Any tips on where I'm going wrong would be greatly appreciated.
You can just convert the two letters into same cases first. Not sure though which case you want to return true.
bool IsAlphaHigher(char letterOne, char letterTwo)
{
if (letterOne > 90) letterOne -= 32;
if (letterTwo > 90) letterTwo -= 32;
return letterOne > letterTwo; // true if letterOne is higher.
}
Simply convert all letters to either uppercase or lowercase before making your comparison.
If you need to preserve the casing, create temporary variables to make the comparison
#include <iostream>
using namespace std;
void alphabetical_order(char first, char second)
{
//65 - 90 are the ascii numbers for upper case letters
if(first >= 65 && first <= 90)
first = tolower(first);
if(second >= 65 && second <= 90)
second = tolower(second);
if(first > second)
cout << first << "," << second << endl;
else
cout << second << "," << first << endl;
}
int main()
{
alphabetical_order('A','Z');
}
Hope this helps you understand, play around with this code and see if it will help you out.
EDIT:
You might want to add error checking with your program to make sure you are given a letter and not a symbol by the way. Check out http://www.asciitable.com/ to get the right numbers. (65 - 90 and 97 - 122)
I am trying to input an binary array which represents a relationship. As an example, the array:
001
000
100
would output (0,2),(2,0)
To do this I'm trying to grab characters one at a time from input, and then change counters based on encountering a newline.
Here is my code so far.
char inChar;
int x = 0;
int y = 0;
while (inChar = ins.get() != '$') {
//$ is used to terminate input
vector <int> orderedPair;
if(inChar == '\n') {
y++;
x=0;
} else {
x++;
}
cout << inChar;
int isPair = inChar - '0';
if(isPair == 1){
orderedPair.push_back(x);
orderedPair.push_back(y);
pointsList.push_back(orderedPair);
orderedPair.clear();
}
}
However, that cout line just outputs... smiley faces? No matter what I enter, I just get smiley faces. I'm lost here. I've looked for any accidentally assignment, and I thought it might be an issue with my typecasting but that is later.
inChar = ins.get() != '$' means inChar = (ins.get() != '$') and whether the character read is equal to '$' or not will be stored to inChar instead of the character itself. You can use (inChar = ins.get()) != '$' to save the input with checking if the input is '$'.
Also note that orderedPair will be cleared on each iteration because it is declared as local variable of the block, so you won't need orderedPair.clear();.
The following code is supposed to make the first character uppercase, as well as any other occurrences of that same character.
For example, if the input is "complication", the output should be "CompliCation". But the output is "Complication" instead.
#include <cctype>
#include <iostream>
#include <string>
int main()
{
std::string cadena;
std::cout << "Write a word: ";
std::cin >> word;
for (int i = 0; i < word.length(); i++)
{
if (word[0] == word[i])
word[i] = std::toupper(word[i]);
}
std::cout << word<< '\n';
}
What is wrong with my code?
By the time you compare the second c, the first c has been converted to C. Hence, Cadena[0] == Cadena[i] is false.
Store the first character first and then compare it with the characters of the string.
char c = Cadena[0];
for (i = 0; i < Cadena.length(); i++)
{
if (c == Cadena[i])
Cadena[i] = toupper(Cadena[i]);
}
You can even pre-compute the uppercase character and use it in the loop.
char c = Cadena[0];
char upperC = toupper(c);
for (i = 0; i < Cadena.length(); i++)
{
if (c == Cadena[i])
Cadena[i] = upperC;
}
Because you make the first character upper case, so the 7th character does not match any more.
Modify your loop like this instead.
char c = Cadena[0];
for (i = 0; i < Cadena.length(); i++)
{
if (Cadena[i] == c)
Cadena[i] = toupper(Cadena[i]);
}
After the first loop Cadena[0] = 'C' so when you encounter another occurrence of this letter, you do the test : if ('C' == 'c') which results to false.
You should first capitalize the characters that are the same to the first character (start your loop at i=1), then capitalize the first character after your for loop.
Because once you apply toupper on the very first character it becomes upper case. Then when it is compared with the same character but lowcase, the comparison returns false. Because 'C' is not the same as 'c'.
can anyone explain how this set of code works ?
string LoginAccess::decryptPass(string pass) {
int count = 0;
while (count < pass.length()) {
if (isalpha(pass[count])) {
//For Caps lock
if (pass[count] > 64 && pass[count] < 91) {
if (pass[count] < 88) {
pass[count] += 3;
} else if (pass[count] == 88) {
pass[count] = 'A';
} else if (pass[count] == 89) {
pass[count] = 'B';
} else
pass[count] = 'C';
//For small char
} else {
if (pass[count] < 120) {
pass[count] += 3;
} else if (pass[count] == 120) {
pass[count] = 'a';
} else if (pass[count] == 121) {
pass[count] = 'b';
} else
pass[count] = 'c';
}
}
count++;
}
return pass;
}
What do the numbers like 64, 91, etc mean?
Why only set it a, b, c ? What happens to the rest of the alphabet?
This function loops the string pass, incrementing count to use as an index for the array. The code is decoding a Ceasar cipher, where each letter is shifted down the alphabet a certain number of places, in this case, three.
It compares the current character (pass[count]) with ASCII character codes. Each letter and punctuation mark has a number associated with it. You can see a chart of characters on this page. As you can see there, the capital letters ('A' through 'Z') span 65 to 90, and the lowercase ('a' through 'z') 97 to 122.
So the code checks whether the letter falls in upper or lower case. There it will by default move the letter three spaces forward, but if it did that with the last three letters of the alphabet, that would push into the number of punctuation. So special coditions are put in to check for that. If pass[count] is 88, the character 'X', it is manually set to 'A', the number 65. If it were incremented by three it would become 91, the character, '['.
There are some weaknesses in the code, as it only supports letters. If punctuation marks were in the pass string, they would be changed into another random punctuation, for no reason from the user's perspective.
#include <iostream>
using namespace std;
Int main() {
cout<<"Give me a letter" <<endl;
char letter;
cin>>letter;
cout<<letter;
(Int)letter;
letter+=2;
cout<<(char)letter;
(Int)letter;
letter-=25;
cout<<(char)letter;
return 0;
}
How would I manipulate the numbers in a way so that the numbers will always output a letter.
ie: if the letter z was chosen and adding 2 is a symbol how would I manipulate it in a way so that it will always stay between the numbers for capital numbers and uncapitalized numbers. Thanks. Please try to keep answers at a beginner level please I am new to this.
if(letter > 'z') {
//do stuff
}
if(letter < 'a' && letter > 'Z') {
//do stuff
}
if(letter < 'A') {
//do stuff
}
It just depends on how you want to handle the character when it goes into one of the three ranges on the ASCII chart in which the characters are not letters.
As a side note, you don't have to cast a char to an int to do math with it.
char myChar = 'a' + 2;
cout << myChar;
This will print: c
c has an ASCII value of 2 more than a.
The surest method is to use a table for each category, and do
your arithmetic on its index, modulo the size of the table.
Thus, for just lower case letters, you might do something like:
char
transcode( char original )
{
char results = original;
static std::string const lower( "abcdefghijklmnopqrstuvwxyz" );
auto pos = std::find( lower.begin(), lower.end(), results );
if ( pos != lower.end() ) {
int index = pos - lower.begin();
index = (index + 2) % lower.size();
results = lower[ index ];
}
return results;
}
This solution is general, and will work regardless of the sets
of letters you want to deal with. For digits (and for upper and
lower case, if you aren't too worried about portability), you
can take advantage of the fact that the code points are
contiguous, and do something like:
char
transcode( char original )
{
char results = original;
if ( results >= '0' && results <= '9' ) {
char tmp = results - '0'
tmp = (tmp + 2) % 10;
results = tmp + '0';
}
return results;
}
An alternative implementation would be to use something like:
results = results + 2;
if ( results > '9' ) {
results -= 10;
}
in the if above. These two solutions are mathematically
equivalent.
This is only guaranteed to work for digits, but will generally
work for upper or lower case if you limit yourself to the
original ASCII character set. (Be aware that most systems today
support extended character sets.)
You can test directly against ASCII chars by using 'x' notation. Further, you can test things together using && ("and" respectively"):
if ('a' <= letter && letter <= 'z') {
// Letter is between 'a' and 'z'
} else if ('A' <= letter && letter <= 'Z')) {
// Letter is between 'A' and 'Z'
} else {
// Error! Letter is not between 'a' and 'z' or 'A' and 'Z'
}
Or you can use the standard library function std::isalpha which handles this for you:
if (std::isalpha(letter)) {
// Letter is between 'a' and 'z' or 'A' and 'Z'
} else {
// Error! Letter is not between 'a' and 'z' or 'A' and 'Z'
}