Pressing certain key - c++

I'm trying to learn C++, my first idea was to make simple win/lost ratio calculator, but it's not working well.
This is my code:
#include<iostream>
#include<conio.h>
using namespace std;
int match=0;
int win=0;
int lose=0;
int ratioo=1;
int total=0;
void lost()
{
if (match=='L');
lose=lose+1;
}
void won()
{
if (match=='W');
win=win+1;
}
int main() {
cout << "Welcome to winratio calculator!" << endl;
cout << "Pressing W adds one win point" << endl;
cout << "Pressing L adds one lose point" << endl;
cout << "Press ENTER to start" << endl;
cout << "Press ESC to close" << endl;
getch();
while(1)
{
cout << "Last game score: ";
cin >> match;
total++;
won();
lost();
ratioo=(win/total)*100;
cout << "Games won: " << win << endl;
cout << "Games lost: " << lose << endl;
cout << "Ratio: " << ratioo <<"%" << endl;
break;
}
return 0;
}
And now my problems:
1)After pressing ANY key there is +1 to win and lose same time
2)I got no idea how to start whole calculator with ENTER and stop it by ESC by getch();, tried few ways but always some errors on the way(it should add points all the time until ESC is pressed
Explanations are very welcome!

Okay, so it looks like we've got a couple of errors in your program as it is now. Let's take a look!
First thing's first. Notice that you have Semicolons at the end of your if statements.
void lost()
{
if (match=='L'); //NOTE: This is a useless if statement
lose=lose+1; //As is, this line will ALWAYS RUN regardless of what character is pressed.
}
void won()
{
if (match=='W'); //Same as Above ^^^^^
win=win+1;
}
Remember that in C, the if statement will execute the next statement conditionally. Remember also that a ; in C is a statement. So, by adding a semicolon after an if statement, you're nullifying the if conditional because the if statement will run the semicolon conditionally, and not your lose = lose + 1;.
Consider writing this instead:
void lost()
{
if (match == 'L')
{
lose = lose + 1;
}
}
void won()
{
if (match == 'W')
{
win = win + 1;
}
}
Furthermore, I noticed that you've inserted a break command to avoid an infinite while(1) loop. To avoid this problem. Consider using match = _getch() instead of cin << match.
match = _getch();
In addition, your Ratioo variable is not receiving anything but 0 due to truncation. To get the percentage you're looking for, you must cast your win/total to double as follows:
ratioo = ((double)win / (double)total) * 100;
So, Now we get to detecting the ESC And ENTER Keys! This is exciting. So, in order to read in these invisible characters, you have to understand that to the computer, these keys are just numbers. The ESC Key is number 27, and the ENTER Key is number 13 (Look Up the ASCII Table for a full list). So To detect them you need to do the following:
match = _getch();
if (match == 27) //27 is the ASCII Code for the Escape Key
{
break;
}
OR Just Substitute 13 if you're looking for the Enter key. By adding A while(1) Loop around it, you can pause a program until that key is pressed (AND ignore all other input).
My Final Version of your Code can be viewed below:
#include<iostream>
#include<conio.h>
using namespace std;
int match = 0;
int win = 0;
int lose = 0;
int ratioo = 1;
int total = 0;
void lost()
{
if (match == 'L')
{
lose = lose + 1;
}
}
void won()
{
if (match == 'W')
{
win = win + 1;
}
}
int main() {
cout << "Welcome to winratio calculator!" << endl;
cout << "Pressing W adds one win point" << endl;
cout << "Pressing L adds one lose point" << endl;
cout << "Press ENTER to start" << endl;
cout << "Press ESC to close" << endl;
while (1)
{
match = _getch();
if (match == 13) //13 is the ASCII Code for the Enter Key
{
break;
}
}
while (1)
{
cout << "Last game score: ";
match = _getch();
if (match == 27) //27 is the ASCII Code for the Escape Key
{
break;
}
total++;
won();
lost();
ratioo = ((double)win / (double)total) * 100;
cout << "Games won: " << win << endl;
cout << "Games lost: " << lose << endl;
cout << "Ratio: " << ratioo << "%" << endl;
}
return 0;
}
Enjoy! And I wish you well towards learning C!

Related

How do I my Program to stop Replicating if wrong input

My program will repeat output: "You are currently on the 2 floor out of 5
The sum of the codes is: 7 and the product of the codes is: 12
Try again before he catches onto you!"
Based on how many wrong characters are added how can I fix this? I have inserted the cin.clear and cin.ignore but it will repeat the part above.
i.e. if I type wasds it will repeat 5x. Any other notes are also appreciated.
#include <iostream>
#include <ctime>
using namespace std;
int PlayerLevel = 0;
int MaxLevel = 5;
bool GamePlay ()
{
srand(time(NULL));
int PlayerGuessA, PlayerGuessB, PlayerGuessC;
int CodeA = rand() % PlayerLevel + PlayerLevel;
int CodeB = rand() % PlayerLevel + PlayerLevel;
int CodeC = rand() % PlayerLevel + PlayerLevel;
int SumofCodes = CodeA + CodeB + CodeC;
int ProductofCodes = CodeA * CodeB * CodeC;
cout << "You are currently on the " << PlayerLevel << " floor out of 5" << endl;
cout << "The sum of the codes is: " << SumofCodes << " and the product of the codes is: " << ProductofCodes << endl;
cin >> PlayerGuessA >> PlayerGuessB >> PlayerGuessC;
int PlayerProduct = PlayerGuessA * PlayerGuessB * PlayerGuessC;
int PlayerSum = PlayerGuessA + PlayerGuessB + PlayerGuessC;
if (PlayerProduct == ProductofCodes && SumofCodes == PlayerSum) {
cout << "Great Job you got this!!!\n" << endl;
++PlayerLevel;
return true;
}
else
{
cout << "Try again before he catches onto you!\n" << endl;
return false;
}
}
int GameStart()
{
string Introduction = "Welcome to your worst nightmare. You are trapped in a murderer's house. You are on the 5th floor and need to get to the first floor to escape.\n";
string Instructions = "He has each door locked behind a security system that requires a 3 number code to disarm it.\nEnter the codes and move foward. Each level will the code will be harder to figure out.\n";
string PlayerStart;
cout << Introduction << endl;
cout << Instructions << endl;
cout << "Would you like to escape? Yes or No" << endl;
cin >> PlayerStart;
if (!(PlayerStart != "Yes" && PlayerStart != "yes")) {
++PlayerLevel;
}
return 0;
}
int main ()
{
if (PlayerLevel == 0) {
GameStart();
}
while (PlayerLevel <= MaxLevel)
{
bool bLevelComplete = GamePlay();
cin.clear ();
cin.ignore();
}
cout << "You Made it out! Now run before he finds out!" << endl;
return 0;
}
When the type of the input doesn't match the type of the variable that it is being extracted to, cin sets the fail bit. Once this happens, all subsequent reads fail until the stream is reset. The offending characters are still left in the buffer, so that needs to be cleared out as well.
Your usage of cin.clear() and cin.ignore() meant that the fail bit was getting reset, but only one offending character was being removed (cin.ignore() ignores one character by default). This is why you saw the output repeating x times for x erroneous characters.
You could do something like this:
while (PlayerLevel <= MaxLevel)
{
bool bLevelComplete = GamePlay();
if (cin.fail())
{
//Input extraction failed, need to reset stream and clear buffer until newline
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
}
}

Conditional cin giving stacked cout messages

Using C++ (g++-4.7 on Mint 16).
Code is a unrefined (and unfinished) Tic-Tac-Toe game.
#include <iostream>
using namespace std;
int main()
{
//initial data
char turn='A';
char ttt[] = {'1','2','3','4','5','6','7','8','9'};
int move;
int over=0; //0 is no, 1 is yes
int valid=0;
while ( over == 0)
{
//display
cout << "\n" << ttt[0] << "|" << ttt[1] << "|" << ttt[2] <<"\n-----\n";
cout << ttt[3] << "|" << ttt[4] << "|" << ttt[5] <<"\n-----\n";
cout << ttt[6] << "|" << ttt[7] << "|" << ttt[8] <<"\n\n Choose a number (Player " << turn << "):";
//ask enter for play with turn
cin >> move;
cout << "\n";
valid = 0;
while (valid == 0)
{
//check if input is valid
if (((move > 0) and (move < 10)) and
((ttt[move-1] != 'A') and (ttt[move-1] != 'B')) and
(cin))
{
ttt[move-1] = turn;
valid=1;
}
else
{
cout << "Invalid slot. Choose a number (Player " << turn << "):";
cin >> move;
cout << "\n";
}
}
//check if done if no //change turn then goto //display
if (((ttt[0]==ttt[1]) and (ttt[1]==ttt[2])) or
((ttt[3]==ttt[4]) and (ttt[4]==ttt[5])) or
((ttt[6]==ttt[7]) and (ttt[7]==ttt[8])) or
((ttt[0]==ttt[3]) and (ttt[3]==ttt[6])) or
((ttt[1]==ttt[4]) and (ttt[4]==ttt[7])) or
((ttt[2]==ttt[5]) and (ttt[5]==ttt[8])) or
((ttt[0]==ttt[4]) and (ttt[4]==ttt[8]))or
((ttt[2]==ttt[4]) and (ttt[4]==ttt[6])))
{
//display winner or say draw
cout << "Player " << turn << " wins!\n";
over=1;
}
else
{
//change turn
if (turn=='A')
{ turn='B';
}
else
{ turn='A';
}
}
}
return 0;
}
There seem to be a bug on the code. On the part where check if input is valid the and (cin) seem to be failing.
When entering a character, (Instead of a number) it output continuously stacks of:
Invalid slot. Choose a number (Player A or B):
I tested the rest of condition without it, it was all working well. Is there a problem on the code or is this really "cin" problem? I've also tried out !(!cin) but it's the same scenario.
You must clear the fail bit from the cin stream in your else block.
When you enter a character that isn't an integer, the cin stream sets the fail bit, which you correctly check for in your if statement, but you never clear it afterward. This causes your input validity check to be false forever.
#include <limits>
...
else
{
cin.clear(); // Add this line
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // And this one
cout << "Invalid slot. Choose a number (Player " << turn << "):";
cin >> move;
cout << "\n";
}
For additional information, see the documentation for std::basic_ios::clear
Update: see this question and this question for similar problems.
Essentially, you also need to tell cin to ignore whatever is in the stream or it will continually set the fail bit with its bad contents you haven't cleared yet. I modified the above snippet to work.

Jumping into c++ chapter 5 prob 7

as recommended I've been working through the book 'Jumping into c++'. I'm currently on problem 7 of chapter 5 and although I have produced the code that appears to do what is asked of me I was hoping someone might be able to take a look and tell me if I've implemented any 'bad' practice (Ideally I don't want to be picking up bad habits already).
Secondly, it also says 'try making a bar graph that shows the results properly scaled to fit on your screen no matter how many results were entered'. Again, the code below produces a horizontal bar graph but I'm not convinced that if I had say 10000 entries (I guess I could verify this by adding an additional for loop) that it would scale according. How would one go about applying this? (such that it always properly scales regardless of how many entries).
I should probably point out at this point that I have not covered topics such as arrays, pointers and classes as of yet in case anyone was curious as to why I didn't just create a class called 'vote' or something.
One final thing... I don't have a 'return 0' in my code, is this a problem? I find it slightly confusing as to what exactly the point of having return 0 is. I know that it's to do with making sure your code is running properly but it seems sort of redundant?
Thanks in advance!
#include <iostream>
using namespace std;
int main()
{
int option;
int option_1 = 0;
int option_2 = 0;
int option_3 = 0;
cout << "Which is your favourite sport?" << endl;
cout << "Tennis.. 1" << endl;
cout << "Football.. 2" << endl;
cout << "Cricket.. 3" << endl;
cin >> option;
while(option != 0)
{
if(option == 1)
{
option_1++;
}
else if(option ==2)
{
option_2++;
}
else if(option ==3)
{
option_3++;
}
else if(option > 3 || option < 0)
{
cout << "Not a valid entry, please enter again" << endl;
}
else if(option ==0)
{
break;
}
cout << "Which is your favourite sport?" << endl;
cout << "Tennis.. 1" << endl;
cout << "Football.. 2" << endl;
cout << "Cricket.. 3" << endl;
cin >> option;
}
cout << "Option 1 (" << option_1 << "): ";
for(int i = 0; i < option_1; i++)
{
cout << "*";
}
cout << "" << endl;
cout << "Option 2 (" << option_2 << "): ";
for(int i = 0; i < option_2; i++)
{
cout << "*";
}
cout << "" << endl;
cout << "Option 3 (" << option_3 << "): ";
for(int i = 0; i < option_3; i++)
{
cout << "*";
}
}
About the return 0 in main : it's optional in C++.
About your code:
You have a ton of if / else if blocks, you should replace them with a switch. A switch statement is more compact, readable, and may be a little bit faster at runtime. It's not important at this point, but it's pretty good practice to know where to put a switch and where to use regular if.
You have one big function, it's really bad. You should break your code into small, reusable pieces. That's something called DRY (Don't repeat Yourself): if you are copy-pasting code, you're doing something wrong. For example, your sport list appears 2 times in your code, you should move it in a separate function.
You wrote cout << "" << endl;, I think you don't really understand how std::cout work. std::cout is an object representing the standard output of your program. You can use operator<< to pass values to this standard output. std::endl is one of these values you can pass, strings are, too. So you can just write cout << endl;, no need for an empty string.
Please learn how to use arrays, either raw ones or std::array. This is a pretty good example of a program which can be refactored using arrays.
Here is a more readable, cleaner version of your code:
#include <iostream>
int prompt_option()
{
int option;
while (true)
{
std::cout << "Which is your favourite sport?" << std::endl;
std::cout << "Tennis.. 1" << std::endl;
std::cout << "Football.. 2" << std::endl;
std::cout << "Cricket.. 3" << std::endl;
std::cin >> option;
if (option >= 0 && option <= 3)
return option;
else
std::cout << "Not a valid entry, please enter again" << std::endl;
}
}
void display_option(int number, int value)
{
std::cout << "Option " << number << " (" << value << "): ";
while (value--)
std::cout << '*';
std::cout << std::endl;
}
int main()
{
int option;
int values[3] = {0};
while (true)
{
option = prompt_option();
if (option)
values[option - 1]++;
else
break;
}
for (int i = 0; i < 3; i++)
display_option(i + 1, values[i]);
}
You have too much if else, it messy.
check out the code bellow, muc shorter, cleaner and efficent.
I hope it helps.
#include <iostream>
using namespace std;
int main()
{
int choice;
int soccer=0, NFL=0 ,formula1=0;
while(choice != 0){
cout<<"Please choose one of the following for the poll"<<endl;
cout<<"press 1 for soccer, press 2 for NFL, press 3 for formula 1"<<endl;
cout<<"Press 0 to exit"<<endl;
cin>>choice;
if(choice==1){
soccer++;
}
else if(choice==2){
NFL++;
}
else if(choice == 3){
formula1++;
}
else{
cout<<"Invalid entry, try again"<<endl;
}
cout<<"soccer chosen "<<soccer<<" times.";
for(int i=0; i<soccer; i++){
cout<<"*";
}
cout<<endl;
cout<<"NFL chosen "<<NFL<<" times.";
for(int j=0; j<NFL; j++){
cout<<"*";
}
cout<<endl;
cout<<"formula1 chosen "<<formula1<<" times.";
for(int c=0; c<formula1; c++){
cout<<"*";
}
cout<<endl;
}
return 0;
}

When using fstream in C++, how can I filter out control and formatting characters?

I have one of those basic assignments where you need to count the numbers of specific types of characters in an input file. There are 3 files involved, the main program (which I will include below), the hopper.txt input text to be analyzed, and the sample output.txt which demonstrates what the output should look like in the command line.
I believe I have everything set but my final numbers arnt turning out correctly. Specifically, my other and total counters are about 200 over. Now I've done some counting with other programs and am pretty sure that the sample output is correct which is why I suspect that I must be counting the hidden characters (and they must be there because the output isn't just a block of text).
I've tried casting each character to an int in order to see what its ascii value is and go off of that range but my IDE (Xcode) says that "comparison of constant with expression of type 'bool' is always true", and the check doesn't seem to catch anything.
Here are the other two files:
hopper.txt
sample output.txt
/***************************************************************
CSCI 240 Program 4 Summer 2013
Programmer:
Date Due: 7/14/14
Purpose: This program reads in the characters from a text file.
While reading them it takes cultivates relivant data about
the frequency of different ascii characters and shares its
results.
***************************************************************/
#include <iostream>
#include <iomanip>
#include <fstream>
#include <unistd.h>
#define FILENAME "/Users/username/Documents/NIU/240/Assigntment\ 4/hopper.txt"
using namespace std;
bool isVowel(char ch);
bool isConsonant(char ch);
int main()
{
ifstream inFile;
inFile.open (FILENAME, ios::in);
char ch;
int t_total = 0;
int t_vowel = 0;
int t_consonant = 0;
int t_letter = 0;
int t_leftParen = 0;
int t_rightParen = 0;
int t_singleQuote = 0;
int t_doubleQuote = 0;
int t_digit = 0;
int t_other = 0;
//See if we successfully imported the file
if (inFile.fail())
{
cout<< "\nThe file entitled: " << FILENAME << " failed to open.\n";
return 0;
}
do
{
//get next letter and print it out
inFile.get (ch);
cout << ch;
//increment total
t_total++;
//check if the character is a letter and if so if it is a vowel or consonant
if(isalpha(ch)){
t_letter++;
//we have found a letter
if(isVowel(ch)) {
t_vowel++;
//we have found a vowel
}
else if(isConsonant(ch)) {
t_consonant++;
//we have found a consonant;
}
else {
cout << "\nYou shouldnt be here...";
}
}
//check if the character is a digit
else if (isdigit(ch)) {
t_digit++;
//we have found a digit
}
//filter out formating characters
else if (!( 32 <= ((int)ch) <= 255)) {
continue;
}
//covers all other cases of askii characters
else {
switch(ch) {
case '(':
t_leftParen++;
break;
case ')':
t_rightParen++;
break;
case '\'':
t_singleQuote++;
break;
case '\"':
t_doubleQuote++;
break;
default:
t_other++;
break;
}
}
} while (inFile);
//These are really just here for the convience of not changing each value while working on formatting
int width1 = 25;
int width2 = 6;
//print out the totals found in the document
cout << "\n\nSummary\n";
cout << fixed << setw(width1) << "\nTotal characters:" << setw(width2) << right << t_total;
cout << fixed << setw(width1) << "\nVowels:" << setw(width2) << right << t_vowel;
cout << fixed << setw(width1) << "\nConsonants:" << setw(width2) << right << t_consonant;
cout << fixed << setw(width1) << "\nLetters:" << setw(width2) << right << t_letter;
cout << fixed << setw(width1) << "\nDigits:" << setw(width2) << right << t_digit;
cout << fixed << setw(width1) << "\nLeft parentheses:" << setw(width2) << right << t_leftParen;
cout << fixed << setw(width1) << "\nRight parentheses:" << setw(width2) << right << t_rightParen;
cout << fixed << setw(width1) << "\nSingle quotes:" << setw(width2) << right << t_singleQuote;
cout << fixed << setw(width1) << "\nDouble quotes:" << setw(width2) << right << t_doubleQuote;
cout << fixed << setw(width1) << "\nOther:" << setw(width2) << right << t_other;
return 0;
}
/***************************************************************
Function: isVowel
Use: Checks if the inputed character is a vowel.
Arguements: 1. ch: A askii character
Returns: true if it is a vowel, false if it is not
***************************************************************/
bool isVowel(char ch) {
//double check we have a letter
if(isalpha(ch)) {
//reduce to lower case to reduce the number of cases that must be checked
ch = tolower(ch);
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
return true;
}
else {
return false;
}
}
return false;
}
/***************************************************************
Function: isConsonant
Use: Checks if the inputed character is a consonant.
Arguements: 1. ch: A askii character
Returns: true if it is a consonant, false if it is not
***************************************************************/
bool isConsonant(char ch) {
//So long as it is a letter, anything that is not a vowel must be a consonant
if(isalpha(ch)) {
return !isVowel(ch);
}
return false;
}
You can use std::isspace to test if a character is one of :
space (0x20, ' ')
form feed (0x0c, '\f')
line feed (0x0a, '\n')
carriage return (0x0d, '\r')
horizontal tab (0x09, '\t')
vertical tab (0x0b, '\v')
And ignore those by adding a test in your reading loop :
else if (std::isspace(ch)) {
continue; // Do not update counters
}

On finding vowels and capitals char in the beginning of a string?

I've been making a little memory game as an exercise from a textbook I'm doing. It's called Grandma's trunk and it works by in one turn you found an item in the trunk and the next turn you say you found the previous item and the newest item on this turn...I think.
Mostly it's an exercise on using functions, which I think I've gotten down pretty well. But my output is completely wrong. I've believe I've located the problem in one function where I'm supposed to analyze the first character and decided if it needs an AN or A or THE before the string. There might be a problem with the random function I'm using to throw in predefined items from a small database. The int main() function is supposed to be relatively complete, this is just an exercise to master functions...which I, sorta? Would rather call it novice experience.
I thought that perhaps I was running into the getline bug where it couts a blank line, and from my understanding, is fixed by cin.ignore(); but all that did was force me to press enter twice when I enter data. Which...I sort of like. Perhaps I'm using gizmos like isupper and .at() wrong? I tried using find_first_of but it didn't really change anything.
output calling the storage trunk and the owner grandma and just using word1 word2 word3... wordn....as items found leaves me with the output.
In grandma trunk you've found a
and an ord3 word1.
it completely muddles up the output. I'm starting to think that the int main() body I was given wasn't exactly stellar. But I can't be 100% confident in my article function. Any help would just be incredible. I've been struggling using this among many books and advice from a buddy to teach myself a little about programming. It's been a rather huge headache.
program itself
#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
using namespace std;
string CorrectArticle(string phrase);
string GetPhrase(void);
bool Continue(void);
string UpperCase(string);
string RandomItem(void);
const string PUNCTUATION = ".";
int main(){
//Variables
int turn;
bool flag;
string phrase,
article,
story, item,
storage, owner;
srand(time(NULL));
cout << "Welcome to Grandmother's Trunk 9000" << endl;
cout << "This is a memory game. Each turn a player" << endl;
cout << "Says an item to place inside a trunk. " << endl;
cout << "And the next player has to say what the " << endl;
cout << "previous player said plus his/her own item." << endl;
cout << "This will go around in revolving turns." << endl;
cout << endl << endl;
cout << "But Grandma's Trunk is a little dry..." << endl;
cout << "Let's change what the storage is and " << endl;
cout << "Who owns it." << endl << endl;
//define storage variable
cout << "What exactly is this storage?" << endl;
getline (cin, storage);
cout << "So the items are stored in " << storage << endl;
cout << endl;
//define owner
cout << "Who owns this " << storage << " ?" << endl;
getline (cin, owner);
cout << "The owner is " << owner << endl;
story = "In "+ owner + " " + storage + " you've found ";
turn = 0;
flag = Continue();
//While flag is true
while (flag) {
if (turn %2 == 0) {
item = GetPhrase();
} else {
item = RandomItem();
}
//set corrected item to article
article = CorrectArticle(item);
//advance the story every item
story = story + "\n and " + article + " " + item;
cout << story << PUNCTUATION << endl;
turn++;
flag = Continue();
}
return (0);
}
//Gives A, AN, and THE to correct words
// An if phrase starts with i,e,i,o,u or y
// A if phrase starts with other lower case letters
// The for phrases that start with an uppercase letter
string CorrectArticle(string phrase){
int i=0;
string correctedString;
string stringAn;
string stringA;
string stringThe;
stringAn= " an ";
stringA = " a ";
stringThe= "The ";
if (GetPhrase().at(i) = "a" or "e" or "i" or "u"){
correctedString = stringAn + GetPhrase();
}else if (isupper(GetPhrase().at(i))){
correctedString = stringThe + GetPhrase();
}else{
correctedString = stringA + GetPhrase();
}
return correctedString;
}
//This function takes no parameters
//and returns the user's input
string GetPhrase(void){
string itemInput;
cout << "\nWhat did you find? \n" << endl;
getline (cin, itemInput);
cout << "\nYou found " << itemInput << endl;
cin.ignore();
return itemInput;
}
//Asks user if they wish to continue
bool Continue(void){
//return false if no, true if yes
string continueString;
cout << "Would you like to continue?";
cout << " Yes or No would suffice" << endl;
getline(cin,continueString);
UpperCase(continueString);
cout << "You picked " << continueString;
if (UpperCase(continueString).find("NO") != string::npos){
return false;
} else if (UpperCase(continueString).find("YES") != string::npos){
return true;
}
}
//Changes the string to uppercase
string UpperCase(string stringUpper){
int i = 0;
while (i<stringUpper.size()){
stringUpper[i] = toupper(stringUpper[i]);
i++;
}
return stringUpper;
}
//Randomizes items found in game
string RandomItem(void){
int randomNumber;
int maxNumberOfItems = 5;
string randomizedItem;
randomNumber= rand() % maxNumberOfItems;
switch (randomNumber){
case 0:
randomizedItem = "Smaug";
break;
case 1:
randomizedItem = "Batman";
break;
case 2:
randomizedItem = "Yoda";
break;
case 3:
randomizedItem = "Paul Atreides";
break;
case 4:
randomizedItem = "Captain Kirk";
break;
default:
cout << "ERRORRRR! PANIC!" << endl;
}
return randomizedItem;
}
Remember that = is assignment, == for compare.
Also remember that you have to compare variable with value, such as:
if ((string == "a") or (string == "e") ...
If the or works for you, all the best. I've only been able to use ||. Must be compiler conformity issues.
Try this:
bool is_vowel(char letter)
{
const std::string vowels("aeiouAEIOU");
return (vowels.find_first(letter) != std::string::npos);
}
In other words, I place all the vowels in a string a search the string. If there is a match, the letter is a vowel.