while (wrongGuess != 6)
{
cout << "\nEnter a letter to guess: ";
cin >> wrongGuess;
wrongGuess = toupper(wrongGuess);
cout << "You guessed the letter: " << wrongGuess << endl;
for (int i = 0; i < fileWord.length(); i++)
{
if (fileWord[i] == wrongGuess)
{
cout << wrongGuess << " is in the letter to guess." << endl;
found = true;
}
}
// if not found - increment wrong guesses
if (!found)
{
wrongGuess++;
cout << wrongGuess << " is not in the word to guess." << endl;
}
//print the board that corresponds to the wrongGuess
}
the first part of the while loop is working it will display the " is in the word to guess." However when I enter an incorrect letter it does not display the " is not in the word to guess" instead it displays "You guessed the letter." What is wrong with my logic?
You are using wrongGuess as the input from the user as well as a counter for the wrong guesses...
Also, I do not know what are the types of wrongGuess and fileWord but my guess is you are comparing an int with a char which might not give the expected result.
I haven't tested this code at all, but it should set you on the way for how you design your program correct.
int guessedLetters = 0;
int guessLeft = 5;
while (guessLeft < 0 || guessedLetters == fileWord.length())
{
char guessInput;
cout << "\nEnter a letter to guess: ";
cin >> guessInput;
guessInput = toupper(guessInput);
cout << "You guessed the letter: " << guessInput<< endl;
for (int i = 0; i < fileWord.length(); i++)
{
if (fileWord[i] == guessInput)
{
cout << wrongGuess << " is in the letter to guess." << endl;
guessedLetters++;
found = true;
}
}
// if not found - increment wrong guesses
if (!found)
{
guessLeft--;
cout << guessInput << " is not in the word to guess." << endl;
}
//print the board that corresponds to the wrongGuess
}
I think you will need another variable, you are using the wrongGuess to control the while and read the input from the user.
I don't know, but try this.
int count = 0;
while (count != 6)
{
cout << "\nEnter a letter to guess: ";
cin >> wrongGuess;
wrongGuess = toupper(wrongGuess);
cout << "You guessed the letter: " << wrongGuess << endl;
for (int i = 0; i < fileWord.length(); i++)
{
if (fileWord[i] == wrongGuess)
{
cout << wrongGuess << " is in the letter to guess." << endl;
found = true;
}
}
// if not found - increment wrong guesses
if (!found)
{
count++;
cout << wrongGuess << " is not in the word to guess." << endl;
}
//print the board that corresponds to the wrongGuess
}
Related
I'm having a problem with the if statement at the end.
**if the sum of the cubs of the number a user inputs, is equal to the number itself, say "....". Else, say "....." **
The problem is that it always jumps the if part to the else.
Its a task from the uni, no homework or nothing, just training. IF you have suggestions on how to better I would appreciate that too.
Thank you!
{
int n;
cout << "Write a number different from 0 -> ";
cin >> n;
while (n == 0)
{
cout << "Choose another number -> ";
cin >> n;
}
cout << "Good number " << n << " is!" << "\n";
cout << "lets separate each digit:" << "\n" << " -----------------------------------" << endl;
Sleep(1000);
vector<int> vecN;
while (n != 0)
{
int digit = n % 10;
n /= 10;
cout << n << endl;
cout << "Digit: " << digit << endl;
vecN.push_back(digit);
Sleep(750);
}
cout << "There you go!" << endl;
Sleep(1000);
cout << "Next stage, let's find the cubes for each one of the digits!" << endl;
Sleep(2500);
vector<int> sums;
for (auto i = vecN.begin(); i != vecN.end(); i++)
{
Sleep(500);
int Cubes = pow(*i, 3);
cout << Cubes << endl;
sums.push_back(Cubes);
}
Sleep(1300);
cout << "Now let's sum the cubs and see if the number is an Armstrong Number" << endl;
Sleep(3000);
int armSum = accumulate(sums.begin(), sums.end(), 0);
if ( armSum == n )
{
cout << "Sum: " << armSum << endl;
Sleep(500);
cout << "That's an Armstrong Number!" << "\n"
"The sum of the cubs of each digit in the number is equal to that same number!" << endl;
}
else
{
cout << "Sum: " << armSum << endl;
Sleep(500);
cout << "That's not an Armstrong Number!" << endl;
}
return 0;
} ```
When the if-part is entered, the else-part won't be entered any more. Note that your if/else is not surrounded by a loop. So when control passes by once, e.g. when having entered n==0, then it has passed by and won't step into neither the if nor the else-part a second time.
Try something like
while (n==0) {
cout << "Choose another number -> ";
cin >> n;
}
// continue here; n is != 0
char playAgain;
do
{
srand(static_cast<unsigned int>(time(0)));
random_shuffle(words.begin(), words.end());
const string THE_WORD = words[0]; //word to guess
int wrong = 0; //number of incorrect guesses
string soFar(THE_WORD.size(), '-'); //word guessed so far
string used = ""; //letter alrdy guessed
cout << "Welcome to Hangman. Good luck!\n";
while ((wrong < MAX_WRONG) && (soFar != THE_WORD))
{
cout << "\n\nYou have " << (MAX_WRONG - wrong);
cout << " incorrect guesses left.\n";
cout << "\nYou've used the following letters:\n" << used << endl;
cout << "\nSo far, the word is:\n" << soFar << endl;
char guess;
cout << "\n\nEnter you guess: ";
cin >> guess;
guess = toupper(guess); //make uppercase since secret word in uppercase
while (used.find(guess) != string::npos)
{
cout << "You've already guessed " << guess << endl;
cout << "Enter you guess: ";
cin >> guess;
guess = toupper(guess);
}
used += guess;
if (THE_WORD.find(guess) != string::npos)
{
cout << "That's right! " << guess << " is in the word.\n";
//update soFar to include newly guessed letter
for (int i = 0; i < THE_WORD.length(); ++i)
{
if (THE_WORD[i] == guess)
{
soFar[i] = guess;
}
}
}
else
{
cout << "Sorry, " << guess << " isn't in the word.\n";
++wrong;
}
}
//shut down
if (wrong == MAX_WRONG)
{
cout << "\nYou've been hanged!";
}
else
{
cout << "\nYou guessed it!";
}
cout << "\nThe word was " << THE_WORD << endl;
cout << "\nPlay again? < Y , N >\n";
cin >> playAgain;
} while ((playAgain == 'Y') || (playAgain == 'y'));
return 0;
Hello, I have tried to make this game be a game which can be repeatable. I succeeded, but noticed that the game only loops once when the player selects either Y or y. This is obviously because playAgain now retains that value. How do I fix this so that playAgain "forgets" what the user input when the game begins again? Thank you for your help.
The only way I see that the loop won't work is if you have characters in the buffer that you haven't read yet, so clear the line with cin.ignore(). You need to #include <limits> for this to work:
...
cout << "\nPlay again? < Y , N >\n";
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if(!(cin >> playAgain)) break; // if extraction fails, we're probably at EOF
) while(...);
What the code does is ask the user which card he wants and prints out a statement depending on which card is chosen.
My aim is to loop back to the card select function if numbers other than 1,2 and 3 are entered.
There is also a for loop which allows this process to go around multiple times.
What is the best way and how can I do this?
int CardSelect() {
cout << "Enter 1 for hearts" << endl;
cout << " " << endl;
cout << "Enter 2 for diamonds" << endl;
cout << " " << endl;
cout << "Enter 3 for joker" << endl;
return 0;
};
int main() {
for (int i = 1; i <= 5; i++) {
CardSelect();
int cardchoice;
cin >> cardchoice;
cardchoice = CardSelect();
if (cardchoice == 1) {
cout << "You got hearts" << endl;
loop = false;
} else if (cardchoice == 2) {
cout << "You got diamonds" << endl;
loop = false;
} else if (cardchoice == 3) {
cout << "You got joker" << endl;
loop = false;
} else {
cout << "Invalid choice" << endl;
cout << "Please ensure you type in the right numbers" << endl;
}
}
}
Change return type of CardSelect() to void, since your simply printing some statements in that function:
void CardSelect()
{ // Your cout statements
}
Call that in main(), and use a switch case for your cardchoice variable.
If you want to keep running the switch statement till you get a valid input, put everything in an inifinte loop (such as a while(1)) and set an exit condition by setting a boolean to true (set it to false initially) and using break when condition is satisified, to get out of the loop:
int main()
{
while(1)
{
bool valid = false;
CardSelect(); // call to your function
int cardchoice;
cin >> cardchoice;
switch(cardchoice)
{
case 1:
cout << "You got hearts" << endl;
valid = true;
break;
case 2:
cout << "You got diamonds" << endl;
valid = true;
break;
case 3:
cout << "You got joker" << endl;
valid = true;
break;
default:
cout << "Invalid choice" << endl;
cout << "Please ensure you type in the right numbers" << endl;
break;
} if(valid) break;
}
}
you should not call cardchoice = CardSelect();.
This call is overwriting cardchoice with 0. Remove this call.
You print values to see what is happening. Its a good way of learning.
Hope this will help.
First, what you are looking for is continue, second you need to get rid of this line which makes no sense :
cardchoice = CardSelect();
as it erases user input
int CardSelect() {
cout << "Enter 1 for hearts" << endl;
cout << " " << endl;
cout << "Enter 2 for diamonds" << endl;
cout << " " << endl;
cout << "Enter 3 for joker" << endl;
return 0;
};
int main() {
for (int i = 1; i <= 5; i++) {
CardSelect();
int cardchoice;
cin >> cardchoice;
if (cardchoice == 1) {
cout << "You got hearts" << endl;
}
else if (cardchoice == 2) {
cout << "You got diamonds" << endl;
}
else if (cardchoice == 3) {
cout << "You got joker" << endl;
}
else {
cout << "Invalid choice" << endl;
cout << "Please ensure you type in the right numbers" << endl;
}
}
}
I am current creating a weather application that is giving me an error. It said there is something wrong with != but I am not sure what is wrong so can anyone help. It is giving me the error operand types are incompatible ("std::string *" and "const char *")(there is 4) and '!=': no conversion from 'const char *' to 'std::string *'
Thank you
C++ code:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
void moveTemperaturesToRight(double temperatures[], double windSpeed[], string windDirection[])
{
for (int i = 3; i > 0; i--)
{
temperatures[i] = temperatures[i - 1];
windSpeed[i] = windSpeed[i - 1];
windDirection[i] = windDirection[i - 1];
}
}
int main()
{
string name;
int choice;
int numOfReadings = 0;
double temperatures[4], windSpeeds[4];
string windDirections[4];
bool initialized = false;
string str;
//Have the user provide a name for the weather station upon entry.
cout << "Enter the name of weather station: ";
getline(cin, name);
//Control loop to perform various actions.
while (true)
{
cout << "1. Input a complete weather reading." << endl;
cout << "2. Print the current weather." << endl;
cout << "3. Print the weather history (from most recent to oldest)." << endl;
cout << "4. Exit the program." << endl;
cout << "Enter your choice: ";
cin >> str;
if (str.length() != 1 || str < "1" || str > "4")
choice = 0;
else
choice = atoi(str.c_str());
//Switch based on choice.
switch (choice)
{
case 1: moveTemperaturesToRight(temperatures, windSpeeds, windDirections);
do {
cout << "Enter the temperature (a value >=0):";
cin >> temperatures[0];
} while (temperatures < 0);
//get correct wind speed
do
{
cout << "Enter the wind speed (a value >=0):";
cin >> windSpeeds[0];
} while (windSpeeds < 0);
//get correct wind direction
do
{
cout << "Enter the wind direction (North,South,East or West):";
cin >> windDirections[0];
} while (windDirections != "North" && windDirections != "South" && windDirections != "East" && windDirections != "West");
initialized = true;
if(initialized)
numOfReadings++;
if (numOfReadings > 4)
numOfReadings = 4;
break;
case 3: //Print the current weather, if valid weather is entered.
for (int i = 0; i < numOfReadings; i++)
{
cout << "*****" << name << "*****" << endl;
cout << "Temperature: " << temperatures[i] << endl;
cout << "Wind speed: " << windSpeeds[i] << endl;
cout << "Wind direction: " << windDirections[i] << endl << endl;
}
if (numOfReadings == 0)
cout << "Please enter the details before asking to print." << endl;
break;
case 2: if (numOfReadings == 0)
{
cout << "Please enter the details before asking to print." << endl;
break;
}
cout << "*****" << name << "*****" << endl;
cout << "Temperature: " << temperatures[0] << endl;
cout << "Wind speed: " << windSpeeds[0] << endl;
cout << "Wind direction: " << windDirections[0] << endl << endl;
break;
case 4: return 0; //Stops execution.
default: cout << "Invalid choice. Please follow the menu." << endl;
}
}
}
You need to compare an element of windDirections with the literal.
Did you mean windDirections[0] != "North" &c.?
Currently you're attempting to compare an array of std::strings, and so the compiler issues a diagnostic. It does its best in decaying the array to a pointer to std::string (hence the specific error), but then gives up.
I am trying to add a countdown timer to this program. I would like the timer to start when the first math fact question is asked and upon expiration i want the program to give the grade. What's the code to do this in c++ if possible?
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cstring>
using namespace std;
int main(int args, char* argv[])
{
int i;
int result;
int solution;
char fact;
bool done = false;
int correct = 0;
int count = 0;
do {
try {
cout << "Enter (m)ultiplication or "
<< "(a)ddition." << endl; /*or (s)ubstraction. */
cin >> fact;
while (!cin)
throw fact;
if (fact != 'A')
if (fact != 'a')
if (fact != 'M')
if (fact != 'm')
while (!cin)
throw fact;
cout << "Now, enter the number of the fact that
you would like to do." << endl;
cin >> i;
int wrong = 0;
int score = 0;
int j = 0;
while (!cin)
throw i;
switch (fact) {
case 'm':
case 'M':
while (j < 13) {
cout << "What's " << i << " x " << j << "?" << endl;
cin >> result;
while (!cin)
throw result;
solution = i * j;
if (result == solution) {
cout << "Great Job! That is the correct answer for the problem "
<< i << " x " << j << "." << endl;
cout << endl;
cout << endl;
cout << endl;
score++;
j++;
cout << endl;
}
if (result != solution) {
cout << "Oh no! " << result << " is NOT the correct answer for "
<< i << " x " << j << "." << endl;
wrong = wrong + 1;
count++;
}
if (count == 3) {
cout << "The correct answer is " << i * j << "." << endl;
j++;
wrong = wrong - 3;
count = 0;
}
if (count == 1) {
cout << endl;
count--;
wrong = wrong - 1;
}
if (count == 2) {
cout << endl;
count--;
wrong = wrong - 2;
}
}
case 'a':
case 'A':
while (j < 13) {
cout << "What's " << i << " + " << j << "?" << endl;
cin >> result;
while (!cin)
throw result;
solution = i + j;
if (result == solution) {
cout << "Great Job! That is the correct answer for the problem "
<< i << " + " << j << "." << endl;
cout << endl;
cout << endl;
cout << endl;
score++;
j++;
cout << endl;
}
if (result != solution) {
cout << "Oh no! " << result << " is NOT the correct answer for "
<< i << " + " << j << "." << endl;
wrong = wrong + 1;
count++;
}
if (count == 3) {
cout << "The correct answer is " << i + j << "." << endl;
j++;
wrong = wrong - 3;
count = 0;
}
if (count == 1) {
cout << endl;
count--;
wrong = wrong - 1;
}
if (count == 2) {
cout << endl;
count--;
wrong = wrong - 2;
}
}
if (j == 13) {
system("pause");
correct = score - wrong;
score = (correct * 100) / 13;
}
if (score >= 80) {
cout << "Excellent!!!!!" << endl;
cout << "You scored " << score << "%." << endl;
cout << "You got " << correct << " out of 13 correct." << endl;
cout << "Keep up the good work." << endl;
} else if (score >= 70) {
cout << "Congratulations!!!!!" << endl
cout << "You scored " << score << "%." << endl;
cout << "You got " << correct << " out of 13 correct." << endl;
cout << "Let's see if we can score even higher next time." << endl;
} else {
cout << "You scored below 70 which means that you may need some"
<< " more practice." << endl;
cout << "You scored " << score << "%." << endl;
cout << "You got " << correct << " out of 13 correct." << endl;
cout << "You might want to try the " << i << " facts again."
<< " Goodluck!!!!!" << endl;
}
}
} catch (char fact) {
cout << "Invalid input. You can only enter (m)ultiplication or"
<< " (a)ddition. Please try again." << endl;
cin.clear();
cin.ignore(100, '\n');
} catch (int i) {
cout << "Invalid input0. You can only enter a
number here. Please try again." << endl;
cin.clear();
cin.ignore(100, '\n');
} catch (...) {
cout << "Invalid input2. You can only enter a number here.
Please try again." << endl;
cin.clear();
cin.ignore(100, '\n');
}
} while (!done);
return 0;
}
The task is quite hard, but if you dare trying, I suggest doing it in two steps:
Implement inaccurate solution: timer expiration is checked between queries to user.
If there is some time left, next question is asked, otherwise statistics is shown. So program always waits for user input on the last question despite timer has run out. Not what exactly quizzes look like, but good move to start with.
Method: before starting quiz save current time, before each question take delta between saved time and current one and compare with time limit. Example with chrono (starting from C++11), example with oldschool clock
Add middle-question interruption
This part requires function, which will wait for user input not longer, than specified amount of time. So instead of using std::cin() you'll need to calculate amount of time left (time limit minus delta between cur time and start time) and call some sort of cin_with_timeout(time_left).
The hardest thing is implementing cin_with_timeout(), which requires solid knowledge of multithreading and thread synchronization. Great inspiration can be found here, but it is direction to start thinking rather than complete solution.