So I basically have to create a small quiz however I'm unsure on how i would re ask the question I would use when the answer is wrong. I believe its a loop but I'm lost on which one. This is what I have so far
#include <iostream>
using std::cin;
using std::cout;
int main() {
std::string answer;
cout << "Is K before T in the alphabet ?";
cin >> answer;
if (answer == "y") {
cout << "Well done!";
}
else {
cout << "Try again";
}
You could do something like this with a simple boolean control variable:
int main()
{
std::string answer;
bool isCorrect = false;
while(isCorrect == false)
{ std::cout << "Is K before T in the alphabet ?";
std::cin >> answer;
if (answer == "y")
{
isCorrect = true;
std::cout << "Well done!";
}
else
{
std::cout << "Try again";
}
}
}
If you plan on having several questions, you can create a helper function and then call it for each question:
bool inputValidation(std::string strQuestion, std::string strAnser) {
std::string userInput;
std::cout << strQuestion;
std::cin >> userInput;
while (true) {
if (userInput == strAnswer)) {
return true;
}
else {
std::cout << strQuestion;
std::cin >> userInput;
}
}
}
int main() {
bool correct = InputValidation("What is the answer?","42");
correct = InputValidation("Is K before T in the alphabet?", "yes");
}
Then you can put all your questions and answers in a map and use a for each loop to cycle through each question-answer pair. If you need multiple outputs, say, "y" == "Yes" == "1", you can pass a vector<std::string> as the answer.
Related
This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 2 years ago.
I'm new to programming and trying a program that You need to guess the name of a video game character, there are only 3 guesses if you ran out of guesses you will lose. I used a do-while loop here so I can do it again and again... The problem here is that every time The loop starts again It displays the prompt 2 times even though It's supposed to be 1 time prompt per guess but it displays 2 prompt. Can you please help me maybe I'm doing the algorithm wrong, Thanks!
#include <iostream>
using namespace std;
int main()
{
char rerun_option;
do {
string secretWord = "Arthur Morgan";
string guess;
int guessCount = 0;
int guessLimit = 3;
bool outofGuesses = false;
while (secretWord != guess && !outofGuesses) {
if (guessCount < guessLimit) {
cout << "Enter video game character name guess: ";
getline(cin, guess);
guessCount++;
}
else {
outofGuesses = true;
}
}
if (outofGuesses) {
cout << "You Lose!" << endl;
outofGuesses = false;
}
else {
cout << "You Win!" << endl;
}
cout << "Try Again?(Y/N) ";
cin >> rerun_option;
} while (rerun_option == 'Y' || rerun_option == 'y');
return 0;
}
EDIT: stackoverflow.com/a/21567292/4645334 is a good example of your problem, explains why you are experiencing it, and explains how you can solve it. I have provided a working example of your code below, as well as a link to more information on the use and description of cin.ignore().
#include <iostream>
using namespace std;
int main()
{
char rerun_option;
do {
string secretWord = "Arthur Morgan";
string guess;
int guessCount = 0;
int guessLimit = 3;
bool outofGuesses = false;
while (secretWord != guess && !outofGuesses) {
if (guessCount < guessLimit) {
cout << "Enter video game character name guess: ";
cin.ignore(); // <-- ADD THIS LINE RIGHT HERE
getline(cin, guess);
guessCount++;
}
else {
outofGuesses = true;
}
}
if (outofGuesses) {
cout << "You Lose!" << endl;
outofGuesses = false;
}
else {
cout << "You Win!" << endl;
}
cout << "Try Again?(Y/N) ";
cin >> rerun_option;
} while (rerun_option == 'Y' || rerun_option == 'y');
return 0;
}
https://www.tutorialspoint.com/what-is-the-use-of-cin-ignore-in-cplusplus
I have only taken one C++ class and am planning on filling my grandma's children's names with different stuff, what I have currently is just filler. However when I try to debug myself by changing string type to integer like it tells me to I then just get new error codes. Here is what I have currently, the program is quite simple:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
string name;
string main() {
bool done = false;
while (!done) {
cout << "Enter one of your children's names, or press 'q' to quit" << endl;
cin >> name;
if (name = "q") {
done = true;
break;
}
else if (name = "Jason") {
cout << "Jason is your eldest son" << endl;
}
else if (name = "Aaron") {
cout << "Aaron was your second child" << endl;
}
else if (name = "Mandy") {
cout << "Mandy is your only girl" << endl;
}
else if (name = "Adam") {
cout << "Adam came after Mandy" << endl;
}
else if (name = "Ben") {
cout << "Ben is your youngest" << endl;
}
else {
cout << "That name does not exist for your children: try Jason, Aaron, Mandy, Adam, or Ben instead" << endl;
}
}
}
On your if and else if statement you need to change == instead of = (assignment) in order to check if the values of two operands are equal or not.
Also, in your String main() I would recommend to change it for just: int main()
Just to reiterate what everyone else has mentioned
Adjust your if/else compare operator ---> if (name == "q")
Use int main()
int main()
{
bool done = false;
string name;
while (!done)
{
if (name == "q")
{
done = true;
break;
}
// Remainder of code goes here
} // Close while loop
} // Close main()
I'll start by saying I have worked on this for 3 days now and this is only my second semester programming. I know this question is probably easy for most, but I really have very little experience.
The code I have written all works as intended except the invalid/blank entry validation. Anything I have found and tried just breaks other parts of the code or doesn't work at all.
Here are the instructions given in the homework for the part I am having issues with:
"Any invalid input for the menu will simply redisplay the menu.
Option 1 will prompt for a userName. An empty name will be ignored."
Here is my code. Any help is greatly appreciated.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<string> usernames;
void listMenu();
void addName();
void listNames();
void removeName();
int main()
{
char entry;
bool exit = false;
while (exit == false)
{
cout << "Choose from the following menu: \n";
listMenu();
cin >> entry;
if (entry == '\n')
{
listNames();
}
if (entry == '1')
{
addName();
}
else if (entry == '2')
{
listNames();
}
else if (entry == '3')
{
removeName();
}
else if (entry == 'x' || entry == 'X')
{
exit = true;
}
}
usernames.clear();
return 0;
}
void listMenu()
{
string menu[4] = { "1. Add a username","2. List all usernames","3. Delete a username","X. Exit" };
for (int i = 0; i < 4; i++) {
cout << menu[i] << endl;
}
}
void addName()
{
string name;
cout << "Enter a username: " << endl;
cin >> name;
usernames.push_back(name);
}
void listNames()
{
int n = 1;
cout << "**************\n";
for (auto& x : usernames)
{
cout << n <<". "<< x <<endl;
n++;
}
cout << "**************\n";
}
void removeName()
{
int x;
cout << "Which username would you like to remove?\n";
listNames;
cin >> x;
usernames.erase(usernames.begin()+x);
}
You can test your input and clear it if it's invalid. Using cin.fail, cin.clear and cin.ignore.
#include<iostream>
using namespace std;
bool cond;
int main() {
int n;
do {
cout << "Enter an integer number:";
cin >> n;
cond = cin.fail();
cin.clear();
cin.ignore(INT_MAX, '\n');
} while(cond);
return 0;
}
I'm trying to write an if/else statement that says 'if the the random question chosen is the first in the array do this ....' etc for all the members of the array. However it is defaulting every question chosen as the first member of the array and carrying out that action. How can I get it to separate that?
if (choice == 1)
{
enum fields{ QUESTS, ANS_1, ANS_2, ANS_3, ANS_4, NUM_FIELDS };
string QUEST[NUM_QUEST][NUM_FIELDS] =
{
{ "What course is this?\n", "A)C++\n", "B)DID\n", "C)Intro to Game\n", "D)Yoga" },
{ "Who am I?\n", "A)Bill\n", "B)Nye\n", "C) 24601\n", "D)No one\n" },
{ "Are you actually reading this?\n", "A) Yes\n", "B)No\n", "C)Maybe\n", "D)Who wants to know?\n" },
{ "Will this program work?\n", "A)Of course it will!\n", "B)It might\n", "C)Are you kidding me?\n", "D)Gods only know." },
{ "Where would I rather be?\n", "A)Home\n", "B)Europe\n", "C)Anywhere but here\n", "D)All of the above\n" }
};
srand(static_cast<unsigned int>(time(0)));
int randomQuest = (rand() % NUM_QUEST);
string question = QUEST[randomQuest][QUESTS];
cout << question;
string printAns1 = QUEST[randomQuest][ANS_1];
string printAns2 = QUEST[randomQuest][ANS_2];
string printAns3 = QUEST[randomQuest][ANS_3];
string printAns4 = QUEST[randomQuest][ANS_4];
cout << printAns1;
cout << printAns2;
cout << printAns3;
cout << printAns4;
cout << "\nAnswer:";
string answer;
cin >> answer;
//PROBLEM IS HERE. KEEPS DEFAULTING TO THIS IF STATEMENT AND IGNORING THE REST SO THAT IT THINKS THE ANSWER IS ALWAYS A
if (question == QUEST[randomQuest][0])
{
if (answer == "A")
{
cout << "Correct. Proceed.";
}
else if (answer != "A")
{
cout << "Failure. Leave. Or, you know, try again.";
}
}
else if (question == QUEST[randomQuest][1])
{
if (answer == "C")
{
cout << "Correct. Proceed.";
}
else if (answer != "C")
{
cout << "Failure. Leave. Or, you know, try again.";
}
}
else if (question == QUEST[randomQuest][2])
{
if (answer == "D")
{
cout << "Correct. Proceed.";
}
else if (answer != "D")
{
cout << "Failure. Leave. Or, you know, try again.";
}
}
else if (question == QUEST[randomQuest][3])
{
if (answer == "C")
{
cout << "Correct. Proceed.";
}
else if (answer != "C")
{
cout << "Failure. Leave. Or, you know, try again.";
}
}
else if (question == QUEST[randomQuest][4])
{
if (answer == "D")
{
cout << "Correct. Proceed.";
}
else if (answer != "D")
{
cout << "Failure. Leave. Or, you know, try again.";
}
}
}
You did not post the full source, so I just posted an example of how I would do this. Even thought it has a few more lines, its much more readable IMHO.
#include <stdio.h>
#include <vector>
#include <string>
struct Question
{
unsigned char answer;
std::string title;
std::vector<std::string> options;
};
int main()
{
std::vector<Question> questions;
// Define the questions
Question questionOne;
Question questionTwo;
Question questionThree;
Question questionFour;
Question questionFive;
questionOne.answer = 'c';
questionOne.title = "What course is this?";
questionOne.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionOne.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionOne.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionOne.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionTwo.answer = 'a';
questionTwo.title = "Who am I?";
questionTwo.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionTwo.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionTwo.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionTwo.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionThree.answer = 'b';
questionThree.title = "Are you actually reading this?";
questionThree.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionThree.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionThree.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionThree.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionFour.answer = 'c';
questionFour.title = "Will this program work?";
questionFour.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionFour.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionFour.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionFour.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionFive.answer = 'd';
questionFive.title = "Where would I rather be?";
questionFive.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionFive.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionFive.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionFive.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
// Save them
questions.push_back(questionOne);
questions.push_back(questionTwo);
questions.push_back(questionThree);
questions.push_back(questionFour);
questions.push_back(questionFive);
// Change to a random question accordingly
for (auto& question : questions)
{
// Show question title
std::cout << question.title << std::endl;
// Show question options
for (auto& option : question.options)
{
std::cout << option << std::endl;
}
// Get the user input accordingly
unsigned char userInput = 0;
// Validate user input
if (userInput == question.answer)
{
std::cout << "Congratulations! Next question coming up..." << std::endl;
}
else
{
std::cout << "Wrong answer. Next question coming up..." << std::endl;
}
}
return 0;
}
Okay, I am very new to try-except. I do-not know if what i'm trying to do is possible, but thought i'd ask for input anyway.
My program is supposed to average x amount of user inputs until he/she enters q.
Here is the function that is giving me the most problems.
vector user_input()
{
vector<double> scores;
string user_command;
do{
double user_input;
cout << "Enter the scores to be averaged (range 0-100) or enter q to quit: " << endl;
cin >> user_command;
if (is_number(user_command))
{
user_input = atof(user_command.c_str());
if (user_input < 0 || user_input > 100)
cout << "This is not within range!" << endl;
else{
scores.push_back(user_input);}
}
}
while (user_command != "q" && user_command != "Q");
return scores;
}
I need some insight on why this program won't compile. Any help would be appreciated
You haven't clearly specified your requirements which makes it difficult to know how to answer the question. I'm assuming you want something like this:
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
typedef double score_type; //so we don't need to write 'double' everywhere, makes it easy to change the type
void user_input(std::vector<score_type>& scores)
{
std::string command;
for (;;)
{
score_type score;
std::cout << "Enter the scores to be averaged (range 0-100) or enter q to quit: " << std::endl;
std::cin >> command;
if (command == "q" || command == "Q")
{
//works better than a do-while in this case
break;
}
try
{
//stod to throw std::invalid_argument and std::out_of_range, check documentation (http://en.cppreference.com/w/cpp/string/basic_string/stof)
score = std::stod(command.c_str());
}
catch (std::exception e)
{
//build exception string
std::ostringstream oss;
oss << "bad input: " << command;
//throw new exception to be handled elsewhere
throw std::exception(oss.str().c_str());
}
if (score < 0 || score > 100)
{
std::cerr << "Input is not within range (0-100)!" << std::endl;
}
scores.push_back(score);
}
}
int main()
{
for (;;)
{
std::vector<score_type> scores;
try
{
user_input(scores);
}
catch (std::exception e)
{
std::cout << "input exception: " << e.what() << std::endl;
}
score_type score_sum = 0;
for (auto score : scores)
{
score_sum += score;
}
score_type average_score = 0;
if (!scores.empty())
{
average_score = score_sum / scores.size();
}
std::cout << "average score: " << average_score << std::endl;
std::cout << "go again? (y/n): " << std::endl;
std::string command;
std::cin >> command;
if (command == "y")
{
continue;
}
else if (command == "n")
{
break;
}
}
}
In future, make sure all the code you post in future questions can be compiled and ran by anyone, especially for simple stuff like this. You can use http://ideone.com/ to test your code samples before posting.