Print out last line and then run program again Y/N - c++

I am stuck on this random guessing game for school.
I have added the code that needed to be added, but the console keeps closing without returning the last strings.
I would also like to learn how to make the program run again with clicking Y to run again.
I am still learning C++, so any help would be appreciated.
Code:
// GuessingGameApp.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>//added to run string
#include <locale>//added toupper run again
using namespace std;
int main()
{
//Seed the random number generator
srand(time(0));
int selectedNumber = rand() % 20 + 1; int numberOfTries = 0;
int inputtedGuess;
std::cout << "Guess My Number Game\n\n";
//Ask the user for a value until the correct number is entered
do {
std::cout << "Enter a guess between 1 and 20:";
std::cin >> inputtedGuess;
++numberOfTries;
if (inputtedGuess > 20 || inputtedGuess < 1) {
cout << "Your guess is out of range.\n\n";
}
else if (inputtedGuess > selectedNumber) {
cout << "Too high!\n\n";
}
else if (inputtedGuess < selectedNumber) {
cout << "Too low!\n\n";
}
}
while (inputtedGuess != selectedNumber);
//Congratulate the user and end the program
std::cout << "\nCongratulations! You solved it in " << numberOfTries << " tries!\n" << std::endl;
//fix problem with console closing and (add "play again" option), so I can
//learn
//printf; did not work... Break did not work..
//
return 0;
}
I was able to get the console to stay open by putting a break at line 33, but I want to learn how to do this correctly so I deleted the break.

The last line of your output should actually be printed. The reason why the last line "is not printed" is probably that your IDE closes the console before you can see the final output (though it should be there). Many IDEs allow to make the console visible after program termination. BTW: Note that when pasting the code you probably lost a << before std::endl in std::cout << "\nCongratulations! You solved it in " << numberOfTries << " tries!\n" std::endl; But this has actually to be a copy-paste problem, because your program would not have compiled otherwise.
Anyway, by providing a "Try again?"-logic, your program does not terminate and the problem is solved.
I'd suggest to provide a separate function performing the guess, which is then called in a do-while loop with the "Try again="-question.
void guess() {
// your code (except srand) goes here...
}
int main() {
srand(time(0)); //Seed the random number generator only once
char doAgain;
do {
guess();
cout << "Try again (Y/N)?";
cin >> doAgain;
}
while (toupper(doAgain)=='Y');
return 0;
}

As people suggested, you can add another do-while loop to repeat the game.
int choice = 0;
do {
// first part of code..
do {
// inner do-while
} while (inputtedGuess != selectedNumber);
std::cout << "\nCongratulations! You solved it in " << numberOfTries << " tries!\n" std::endl;
cout << "\nWould you like to play again?\n\n";
cout << "1 - Yes\n";
cout << "2 - No\n\n";
cout << "Choice: ";
cin >> choice;
} while(choice == 1);

Related

Elements are reading out of array of strings, but can't be compared

I'm coding a simple custom shell in UNIX and I want to retrieve a specific command string from an array of commands that I loaded in from an external file. I know that my array successfully loaded the commands as all 7 of them are printing out, so I know they are there. However, when I enter in, say, 'mypwd' as input to be retrieved from the array, I get nothing back.
What I've done is I hard coded in the string I want to be read
if(command.compare("mypwd") == 0)
and
if(command.compare(0,5,"mypwd") == 0)
the program recognizes and executes my command, but when I try to call if from where it is stored in the array,
if(command.compare(command_array[0]) == 0)
and i've also tried
if(command.substr(0, 5).compare(command_array[0]) == 0)
my else statement error gets thrown.
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
// global variables
string username;
string password;
string command_array[7];
int COUNT = 0;
void mypwd();
void build_command();
int main()
{
int i=0,opcode=0;
int pid=0, status=0, background=0;
string command, parameters[3];
build_command();
int numberOfElements = COUNT;
cout << "........................\n" << endl;
cout << "List of commands loaded.\n" << endl;
cout << "........................\n" << endl;
//Print all commands.
for(int c = 0; c < numberOfElements; c++)
{
cout << command_array[c] << endl;
}
//Enter command you want to run
cout << "\Enter command: ";
cin >> command;
//Get the command.
if(command.compare(command_array[0]) == 0)
{
cout << "You've read the " << command << " command!";
}else
{
cout << "Command not read." << endl;
}
return 0;
}
void build_command()
{
ifstream COMMANDFILE;
string GETCOMMAND;
COMMANDFILE.open("commands.txt");
if(COMMANDFILE.is_open())
{
while(getline(COMMANDFILE, GETCOMMAND))
{
command_array[COUNT] = GETCOMMAND;
COUNT++;
}
}
COMMANDFILE.close();
}
void mypwd()
{
ofstream TO_CHANGE;
TO_CHANGE.open("users.txt");
if(TO_CHANGE.is_open())
{
cout << "Enter new password:";
cin >> password;
TO_CHANGE << username << ":" << password;
TO_CHANGE.close();
}
}
The output that is currently happening is
mypwd
mycopy
myps
mydf
mysearch
myhistory
mylogout
Enter command: mypwd
"Command not read."
The only other thing I could come up to solving this problem is maybe loading them into a string of vectors and having them compared that way using the std::vector library or possibly using strtok() but at this point, I'm mostly curious as to what I'm doing wrong in my code.
The only possibility is that there's whitespace at the end of your commands. Can you change:
cout << command_array[c] << endl;
For
cout << command_array[c] << " " << command_array[c].size() << endl;
One you confirm there's extra characters, then you'll have to think about stripping the extra whitespace.
I ended up fixing my problem by changing my comparison line to
if(command == command_array[0].substr(0,5))
instead of
if(command.compare(command_array[0]) == 0)
by setting the substr at the end returned the substring of the element at index [0] and thereby stripping off the extra whitespace in the string. It's not the optimal solution, but it solves my problem.

cin not accepting user input in C++

I'm a beginner in programming, and I'm trying to make a program that calculated how much radiation you've been exposed to throughout your life. For some reason, the 'cin' in my xray function doesn't accept user input, and just exits with code 0.
#include <iostream>
#include <conio.h>
#include <windows.h>
#include <stdlib.h>
#include <string>
#include <sstream>
using namespace std;
bool nearpowerplant;
int XRay; // the amount of times you got an x-ray
double tRads = 0; // your total dose of radiation in your lifetime, measured in mSv (millisievert)
int age;
//the sleep function
void sleep() {
Sleep(1000); // 1000 miliseconds = 1 second
}
/*
>system("CLS")< for clear the console
*/
//introduction and pretty much the menu
void intro() {
cout << "Welcome to the Radiation Level Calculator" << endl;
sleep();
cout << "Conceptualized and created by Anatoly Zavyalov" << endl;
sleep();
cout << "Press the ENTER key to begin." << endl;
cin.get();
}
//introduction to general questions
void genintro() {
// intro to the medical
system("CLS");
sleep();
cout << "Let's begin with general questions." << endl;
sleep();
cout << "Press the ENTER key to continue." << endl;
cin.get();
}
//medical questions
void Age() {
//age
system("CLS");
cout << "How old are you?\n" << endl;
sleep();
cin >> age;
if (age <= 0) {
cout << "Your age can't be less or equal to 0." << endl;
Age();
}
else {
tRads += (age * 2);
sleep();
cout << tRads << endl;
}
}
//live close to powerplant?
void powerplant() {
system("CLS");
cout << "Do you live within 75 kilometers of a nuclear powerplant?" << endl;
sleep();
cout << "If yes, type YES. If no, type NO." << endl;
cin >> nearpowerplant;
if (nearpowerplant = "YES") {
tRads += (age * 0.01);
}
else {}
sleep();
cout << tRads << endl;
}
void xray() {
system("CLS");
cout << "How many times have you had an x-ray?\n" << endl;
sleep();
cin >> XRay;
if (XRay < 0) {
cout << "You can't have an x-ray a negative amount of times." << endl;
}
else {
tRads += (XRay * 3.1);
}
sleep();
cout << tRads << endl;
}
//main function, put all of the loops into here
int main() {
intro(); // the introduction
genintro(); // medical intro
Age(); // asks for age
powerplant(); // asks if lives close to powerplant
xray(); // asks for x-ray
return 0;
}
EDIT: I have edited the post to include the whole code. By the way, I am using Visual Studio Community 2017.
bool nearpowerplant;
nearpowerplant is a bool. It is true or false. That is it. It's worth noting that there is no reason for this variable to be globally accessible and consuming storage for the entire run of the program. It is used twice in the program, both times in the same function. It should be an Automatic variable scoped by the function that uses it.
cout << "If yes, type YES. If no, type NO." << endl;
cin >> nearpowerplant;
Reading "YES" or "NO" into a variable of type bool fails. cin cannot convert the string input into a boolean value and cin stops accepting input until the error is cleared. It's also a good idea to remove the garbage input that caused cin to fail or guess what? cin's just going to fail again. There are hundreds of SO questions on how to handle this, so I'm just going to drop keywords here: clear and ignore.
Takeaways: Make sure the data entry matches the type of the data being entered into and test the stream after every read to make sure the read succeeded.
eg:
if (cin >> nearpowerplant)
{
// do stuff
}
else
{
// clean up
}
This solves OP's visible error, but since it is heavily entwined with the next bug they are likely to find, we might as well cover it as well.
if (nearpowerplant = "YES") {
tRads += (age * 0.01);
}
else {}
if (nearpowerplant = "YES") { uses = (assignment) where it should use == (comparison). C++ is unforgiving here because this will compile. What it really did was takes the address of the string literal "YES", test that it's not null, and set nearpowerplant to the result. Since the address of the string literal is never going to be NULL, the result is always true, and when the if tests the result, the if will always enter.
Eg: http://ideone.com/4QL2jn
So what we need is something more like
cout << "If yes, type YES. If no, type NO." << endl;
string temp;
cin >> temp;
if (temp == "YES") {
tRads += (age * 0.01);
}
else {}
Note this will skip if the user inputs "yes", "y", "Yes" or anything other than exactly "YES". How you deal with this is up to you, but std::tolower and std::transform may help somewhat.
I think with sleep() comes undefined behavior, you should test it without, the os handles user-input and you do not have to care about the user typing in. endl flushes cout, so the text is directly shown.
Edit:
Maybe system("CLS") or sleep produces a silent error.

Why does this cause in infinite loop with chars but not doubles?

I feel like im doing something really silly wrong. I just want the program to tell the user when they are entering non-doubles, and continue to loop back to the cin where you enter a value.
I want the user to input any number. Then essential do this trivial math and repeat. Its working fine in that regard, the problem comes when some unexpected input like a char gets entered. Then the input somehow sends it into a loop where it loops the math problem, instead of just telling the user that they must type a number and looping back to cin type in a new number.
#include <iostream>
#include <cstdlib>
using std::cout; using std::cin; using std::endl;
long double domath(long double i)
{
cout << i << "/" << 2 << "=" << i/2 << endl;
cout << i/2 << "*" << 10 << "=" << (i/2)*10 << endl << endl;
cout << 5 << "*" << i << "=" << 5*i << "\n\n";
return 0;
}
int main()
{
long double in = 0;
while(true)
{
cin >> in;
if (cin.fail()) {
in = char(int(in));
}
domath(in);
}
system("pause>nul");
return 0;
}
You don't clear the cin in case of fail, and it infinitely tries to parse wrong input to double, failing every time. You need to clear the buffer in case of error:
if (cin.fail()) {
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
in = char(int(in));
}
Also, can't understand what you're trying to achieve with
in = char(int(in));
in is a long double variable and will hold the last value you assigned to it, no need to "convert" it to do math.
Couldn't you try doing something like this?
int x;
if(std::cin >> x)
doSomethingCool(x);
else
std::cout << "Error, not a valid integer!" << std::endl;
Exit your loop on bad input.
I think this just feels more natural/looks cleaner than clearing the buffer and all the other jazz. Just my opinion.
if (cin >> x) - Why can you use that condition?
edit: Bul's answer is still a good one though.

C++ Code Results in Possible Console Output Error

I am running this code from textbook: An Intro To Design Patterns in C++ with QT.
/* Computes and prints n! for a given n.
Uses several basic elements of C++. */
#include <iostream>
int main() {
using namespace std;
/*
*/
// Declarations of variables
int factArg = 0;
int fact(1);
do {
cout << "Factorial of: ";
cin >> factArg;
if (factArg < 0) {
cout << "No negative values, please!" << endl;
}
}
while (factArg < 0);
int i = 2;
while (i <= factArg) {
fact = fact * i;
i = i + 1;
}
cout << "The Factorial of " << factArg << " is: " << fact << endl;
return 0;
}
The output console only prints one line that says "Factorial is: "
Is that what it's suppose to do?
Yes that is what the program should output at first; it's waiting for you to type a number. If you would step into your code you would soon find out that it will wait for an input on the following line " cin >> factArg;".
So... Go ahead, type a number and press enter :).
Yes you code includes cin >> factArgwhich you will input in the terminal first before the program will run. You may want to put the using namespace std before the main function rather then in it.

Do-while loop issue: Try to develop a simple game

Well, I'm writing to make a dice game. I tried searching dice game here but none of it seems to answer my question. This isn't a problem about the dice roll thing anyway. It's about the do while loop. I am very new to this site, I just found out about this via Maximum PC Magazine so please bear with me. Also I am new to programming.
Here is my code:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(){
srand(time(NULL));
int userRoll = rand() % 6 + 1 ;
int computerRoll = rand() % 6 + 1 ;
string yesOrNoChoice;
string commandToThrowDie;
do{
cout << "Please enter \"throw\" (lowercase) to roll the die: ";
cin >> commandToThrowDie;
} while(commandToThrowDie != "throw");
do{
cout << "You rolled: " << userRoll << endl
<< "The Computer rolled: " << computerRoll << endl;
if (userRoll < computerRoll){
cout << "You lose. Try again? [Yes/No]: ";
}
if (computerRoll < userRoll){
cout << "You win! Try again? [Yes/No]: ";
}
if (computerRoll == userRoll) {
cout << "It's a draw. Try again? [Yes/No]: ";
}
cin >> yesOrNoChoice;
} while(yesOrNoChoice != "Yes");
system ("pause");
return 0;
}
The problem is that after asking the user to enter a choice at the end of the do-while-loop the program exits loop no matter what I enter, instead of looping back to another throw of the die.
It ends up like this:
I copied your code and it compiled and ran perfectly. Doesn't make sense exactly, but no issues. I say it doesn't make sense since when "Yes" is entered that is what kills it. I believe what you want it while(yesOrNoChoice == "Yes"). Perhaps having it as != was making you think you were getting the wrong behavior? Also, you should be using if, else if, else statements, not just if.