Program to calculate difference between two times for "time travel" - c++

I am writing a "time travel" program which is supposed to ask the user for the current time, their target travel time, relay those values to be converted into minutes in a function and then based on if the time difference is too high it will not allow the time travel or if it is allowed it will print if they are in the future or the past. My issue right now is that the current time, which is only supposed to be relevant the first iteration, or the first "jump" of the program is not being updated after the jump occurs, and the program defaults to it instead of the target time, which is supposed to be the technical "current time" after the jump has occurred. I have been trying to figure this out for hours and I can't, so I am hoping someone could help me out.
Thank you for your time
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int compute_time_difference(int c_hrs, int c_mins, bool c_am, int t_hrs, int t_mins, bool t_am);
void print_future();
void print_past();
void print_SecurityProtocol();
int main()
{
int c_hrs, c_mins;
int t_hrs, t_mins;
int system_time2;
int time_difference2;
bool c_am = 0;
bool t_am = 0;
char c, c2, Y, N, y, n, jumpAgain;
string am_or_pm_current, am_or_pm_target;
bool g_stop = true;
cout << "Welcome to Po Sled" << endl;
cout << "\tSystem booting..." << endl;
for (int i = 0; i<1; i++) //for loop to run once
{
cout << "\n\tEnter current time below: " << endl;
cout << "\t>Enter hour: "; //User inputs current time in hours
cin >> c_hrs;
while (c_hrs > 12 || c_hrs < 1)
{
cout << "Error: Please enter an hour in the range [1, 12]: ";
cin >> c_hrs;
}
cout << "\t>Enter minutes: "; //User inputs current time in minutes
cin >> c_mins;
while (c_mins > 59 || c_mins < 0) {
cout << "Error: Please enter minutes in the range [0, 59]: ";
cin >> c_mins;
}
cout << "\t>Is it AM or PM?: "; //Classifying if current time is AM or PM
cin >> am_or_pm_current;
while (am_or_pm_current != "am" && am_or_pm_current != "AM" && am_or_pm_current != "pm" && am_or_pm_current != "PM") { //Checks if valid input, if not repeats message until valid
cout << "\tError: Please enter AM/am or PM/pm: ";
cin >> am_or_pm_current;
}
if ((am_or_pm_current == "am") || (am_or_pm_current == "AM"))
{
c_am = 1;
}
else if ((am_or_pm_current == "pm") || (am_or_pm_current == "PM"))
{
c_am = 0;
}
cout << "\n\tCurrent system time set to " << c_hrs << ":" << setw(2) << setfill('0') << c_mins << am_or_pm_current << endl;
cout << "\n\t\tIs this time correct (Y or N)? ";
cin >> c;
while (c != 'Y' && c != 'y' && c != 'n' && c != 'N')
{
cout << "\t\t\tError: Please enter Y/y or N/n: ";
cin >> c;
}
if (c == 'N' || c == 'n')
{
continue;
}
else
{
cout << "\n\tSystem initializing and TARDIS unit warming...." << endl;
cout << "\tThe Po Sled is engaged and ready for input." << endl;
}
}
do {
//Starts a loop for target jump
cout << "\n\tEnter target time below: " << endl; //Enters target time of jump
cout << "\t>Enter Hour: ";
cin >> t_hrs;
while (t_hrs > 12 || t_hrs < 1) {
cout << "Error: Please enter an hour in the range [1, 12]: ";
cin >> t_hrs;
}
cout << "\t>Enter minutes: ";
cin >> t_mins;
while (t_mins > 59 || t_mins < 0) {
cout << "\tError: Please enter minutes in the range [0, 59]: ";
cin >> t_mins;
}
cout << "\n\tIs it AM or PM?: ";
cin >> am_or_pm_target; //Classifying if target time is AM or PM
while (am_or_pm_current != "am" && am_or_pm_current != "AM" && am_or_pm_current != "pm" && am_or_pm_current != "PM")
{ //Validates input is AM or PM
cout << "\tError: Please enter AM/am or PM/pm: ";
cin >> am_or_pm_target;
}
if ((am_or_pm_target == "am") || (am_or_pm_target == "AM"))
{
t_am = 1;
}
else if ((am_or_pm_target == "pm") || (am_or_pm_target == "PM"))
{
t_am = 0;
}
cout << "\tTarget time set to " << t_hrs << ":" << setw(2) << setfill('0') << t_mins << am_or_pm_target; //Sets target time
cout << "\n\t\tIs this time correct (Y or N)? "; //Validates if target time entered is correct
cin >> c2;
while (c2 != 'Y' && c2 != 'y' && c2 != 'n' && c2 != 'N')
{
cout << "\t\t\tError: Please enter Y/y or N/n: ";
cin >> c2;
}
time_difference2 = compute_time_difference(c_hrs, c_mins, c_am, t_hrs, t_mins, t_am);
if (time_difference2 > 360) //If time difference is greater than 6 hours prints error function
{
print_SecurityProtocol();
continue;
}
if (c2 == 'N' || c2 == 'n')
{
continue;
}
cout << "\tJump was made, the current time is " << t_hrs << ":" << setw(2) << setfill('0') << t_mins << am_or_pm_target << endl;
if (time_difference2 < 0 && time_difference2 > -360) //If time difference is less than 0 prints past function
{
print_past();
}
else if (time_difference2 >= 0 && time_difference2 <= 360) //If time difference is ahead of current time prints future function
{
print_future();
}
cout << "\tWould you like to jump again (Y/N)? ";
cin >> jumpAgain;
while (jumpAgain != 'Y' && jumpAgain != 'y' && jumpAgain != 'n' && jumpAgain != 'N') //Input validation
{
cout << "\t\t\tError: Please enter Y/y or N/n: ";
cin >> jumpAgain;
}
if (jumpAgain == 'n' || jumpAgain == 'N') //User exiting program
{
if (time_difference2 < 0)
{
cout << "\t\tSystem shutting down; enjoy the past.\n" << endl;
}
else if (time_difference2 >= 0 && time_difference2 < 360)
{
cout << "\t\tSystem shutting down; enjoy the future.\n" << endl;
}
}
if (jumpAgain == 'Y' || jumpAgain == 'y')
{
continue;
}
} while (jumpAgain != 'n' && jumpAgain != 'N');
return 0;
}
int compute_time_difference(int c_hrs, int c_mins, bool c_am, int t_hrs, int t_mins, bool t_am) //Computes time differences.
{
int currentTime_hours, currentTime_minutes, targetTime_hours, targetTime_minutes, currentTime, targetTime;
int time_difference;
if (c_am == 1) //if c_am is true and it is morning
{
if (c_hrs == 12)
{
currentTime_hours = c_hrs * 0;
}
else if (c_hrs != 12)
{
currentTime_hours = (c_hrs * 60);
currentTime_minutes = c_mins;
currentTime = currentTime_hours + currentTime_minutes; //Sets the value of the current time
}
}
else if (c_am == 0) //if c_am is false and it is afternoon time
{
if (currentTime_hours == 12)
{
c_hrs = c_hrs * 60;
}
else if (currentTime_hours != 12)
{
currentTime_hours = ((c_hrs + 12) * 60);
currentTime_minutes = c_mins;
currentTime = currentTime_hours + currentTime_minutes; //Sets the value of the current time
}
}
if (t_am == 1) //if t_am is true and it is morning time
{
if (targetTime_hours == 12) //if target hours equal to 12 special math
{
targetTime_hours = t_hrs*0;
}
else if (targetTime_hours != 12) //else do this math
{
targetTime_hours = ((t_hrs) * 60);
targetTime_minutes = t_mins;
targetTime = targetTime_hours + targetTime_minutes;
}
}
else if (t_am == 0) //if target time equal to pm then do this math
{
if (targetTime_hours == 12)
{
targetTime_hours = t_hrs * 60;
}
else if (targetTime_hours != 12) //else if target time not equal to 12 then do normal pm math
{
targetTime_hours = ((t_hrs + 12) * 60);
targetTime_minutes = t_mins;
targetTime = targetTime_hours + targetTime_minutes;
}
}
time_difference = targetTime - currentTime;
cout << "the difference computed is " << time_difference;
return time_difference;
}
void print_SecurityProtocol() //Function which prints security protocol error message
{
cout << "\tSecurity Protocols Engaging" << endl;
cout << "\t\tError: The time difference is greater than 6 hours." << endl;
cout << "\t\t\tPlease re-enter target time." << endl;
}
void print_past() //Function that prints when a user is in the past
{
cout << "\tHold onto your lower posterior regions" << endl;
cout << "\n\t\tYou are now in the relative past" << endl;
}
void print_future() //Function that prints when a user is in the future
{
cout << "\tHold onto your lower posterior regions" << endl;
cout << "\n\t\tYou are now in the relative future " << endl;
}

Why do you not use a system time call, instead of getting user input for the 'current time'? Also, use a 24-hour clock instead of a 12-hour and you have removed the need to cater for am/pm within your process.
AM n ot much of a coder but c_hrs*60 would be (at least) 60 hours and (at most) 24*60 which, with the exception of a drive across Europe, Russia, Australia or the Northern US would be excessive time recording. Do you not mean to refer to MINUTES instead of hours (c_mins*60)?

Related

calling function on while loop

I'm making a calculator program but I already encounter a problem. Well, my code is in a loop that will call a function to display the choices and then ask the user to pick, a/s/m/d are the choices. If the input is on the choices, it will proceed to the next step. Otherwise, it will loop and then call the function again.
#include <iostream>
using namespace std;
void home()
{
cout << "\nChoose your operation:" << endl;
cout << "\tType [A] for Addition" << endl;
cout << "\tType [S] for Subtraction"<< endl;
cout << "\tType [M] for Multiplication" << endl;
cout << "\tType [D] for Division" << endl;
}
int main()
{
char operation;
bool no_operator = true;
int design = 73;
for (int i = 0; i < design; i++){
if (i == 25){
cout << " WELCOME TO CALCULATOR ";
i += 22;
}
else i == 72 ? cout << "*\n" : cout << "*";
}
while (no_operator){
home();
cout << "\nOperation: ";
cin >> operation;
if (operation == 'A' || operation == 'a')
{
cout << "\nIt will going to add numbers";
no_operator = false;
}
else if (operation == 'S' || operation == 's')
{
no_operator = false;
cout << "\nIt will going to subtract numbers";
}
else if (operation == 'M' || operation == 'm')
{
no_operator = false;
cout << "\nIt will going to multiply numbers";
}
else if (operation == 'D' || operation == 'd')
{
no_operator = false;
cout << "\nIt will going to divide numbers";
}
else
{
cout << "\tInvalid Input: You must enter A/S/M/D only\n";
//home();
}
}
return 0;
}
My problem is it will run the '''home()''' in else statement even if the input is correct on the second loop.
I want to stop the '''home()''' to be called when the input is correct
Your code works perfectly fine. Make sure you're inputting the correct letters.
Also for this code, a "do while()" loop would be better.
You program is working perfectly fine as the input is correct it does not show the home rather print the message it will going to divide etc.

c++ loops and boolean expressions

I'm having trouble trying to do this assignment for my class for a couple of days now and would like some help.
The assignment is to write a program that informs the user of their acceptance status based on their heigh and weight qualifications depending on their gender.
At the end of the program it wants to output the number of candidates that were accepted and the average of those accepted to the overall number of candidates.
Assignment - https://www.saddleback.edu/faculty/slinker/CS1A/CS1A_Fall2013/Assignment8.pdf
We can't use switch, conditional operators, and selection (only for outputting the correct message to the results). We can only use loops and complex boolean expressions
The problems I'm having is:
If all 3 of my inputs are valid, why are they not outputting if they are accepted and if one of the input (height or weight) or both were rejected then why isn't it outputting it. Is my boolean variable incorrect? If so, how do I fix it.
Why am i unable to exit the loop/program when I enter X. Is my while loop correct or no?
Is there any selection statements I can change into "not selection-statements".
Here is my code
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
char gender;
int height;
int weight;
bool heightOK;
bool weightOK;
int candidateCount;
int validCandidateCount;
bool invalidGender;
bool invalidHeight;
bool invalidWeight;
float percentOutput;
candidateCount = 0;
validCandidateCount = 0;
cout << "Please enter the candidate's information (enter 'X' to exit)."
<< endl;
do
{
cout << "Gender: ";
cin.get(gender);
cin.ignore (1000,'\n');
invalidGender = ( !(gender == 'm' ||
gender == 'M' ||
gender == 'f' ||
gender == 'F' ));
candidateCount = candidateCount + 1;
if(invalidGender)
{
cout << "***** Invalid gender; please enter M or F*****" << endl;
}
}while(invalidGender);
while (gender != 'X' || gender != 'x')
{
candidateCount = candidateCount + 1;
do
{
cout << "Height: ";
cin >> height;
invalidHeight = height < 24 || height > 110;
heightOK = ((gender == 'm' || gender == 'M') &&
(height > 65 && height < 80));
heightOK = heightOK || ((gender == 'f' || gender == 'F') &&
(height > 62 && height < 75));
if(invalidHeight)
{
cout << "***** Invalid height; please enter a height in inches between 24 and 110. *****"
<< endl;
}
}while(invalidHeight);
do
{
cout << "Weight: ";
cin >> weight;
invalidWeight = weight < 50 || weight > 1400;
weightOK = ((gender == 'm' || gender == 'M') &&
(weight > 130 && weight < 250));
weightOK = weightOK || ((gender == 'f' || gender == 'F') &&
(weight > 110 && weight < 185));
if(invalidWeight)
{
cout << "***** Invalid weight; please enter a weight in lbs between 50 and 1400."
<< endl;
}
}while(invalidWeight);
if(heightOK && weightOK)
{
cout << "This candidate has been ACCEPTED!" << endl;
validCandidateCount = validCandidateCount + 1;
}
else if (!heightOK)
{
cout << "This candidate has been rejected based on the HEIGHT requirement."
<< endl;
}
else if (!weightOK)
{
cout << "This candidate has been rejected based on the WEIGHT requirement."
<< endl;
}
else if (!(heightOK && weightOK))
{
cout << "This candidate has been rejected based on the HEIGHT and WEIGHT requirements"
<< endl;
}
do
{
cout << "Gender: ";
cin.get(gender);
cin.ignore (1000,'\n');
candidateCount = candidateCount + 1;
if(invalidGender)
{
cout << "***** Invalid gender; please enter M or F*****" << endl;
}
}while(invalidGender);
}
cout << validCandidateCount << " candidate(s) accepted!" << endl;
percentOutput = validCandidateCount / candidateCount;
cout << "That's " << percentOutput <<"%!" << endl;
return 0;
}
The main while loop should have and condition.
while(gender !='X' && gender!='x)
And your selection code has wrong conditional statements.
if(heightOK && weightOK)
{
cout << "This candidate has been ACCEPTED!" << endl;
validCandidateCount = validCandidateCount + 1;
}
else if (!heightOK) // you have written else if(heightOK)
{
cout << "This candidate has been rejected based on the HEIGHT requirement."
<< endl;
}
else if (!weightOK) // you have written else if(weightOK)
{
cout << "This candidate has been rejected based on the WEIGHT requirement."
<< endl;
}
else if (!(heightOK && weightOK))
{
cout << "This candidate has been rejected based on the HEIGHT and WEIGHT requirements"
<< endl;
}
You should remove that invalidgender condition in the last do while loop, otherwise it will cause an infinite loop even if you wish to exit by pressing X.
Instead the invalid gender condition can be placed at the starting of main While loop.
And invalidGender variable should be assigned its value again otherwise it will pick up the previously stored value.
invalidGender = ( !(gender == 'm' ||
gender == 'M' ||
gender == 'f' ||
gender == 'F' ));
the whole code
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
char gender;
int height;
int weight;
bool heightOK;
bool weightOK;
int candidateCount;
int validCandidateCount;
bool invalidGender;
bool invalidHeight;
bool invalidWeight;
double percentOutput;
candidateCount = 0;
validCandidateCount = 0;
cout << "Please enter the candidate's information (enter 'X' to exit)."
<< endl;
cout << "Gender: ";
cin.get(gender);
while (gender != 'X' && gender != 'x')
{
candidateCount = candidateCount + 1;
do
{
invalidGender = ( !(gender == 'm' ||
gender == 'M' ||
gender == 'f' ||
gender == 'F' ));
if(invalidGender)
{
cout << "***** Invalid gender; please enter M or F*****" << endl;
cout << "Gender: ";
cin>>gender;
cin.ignore (1000,'\n');
}
}while(invalidGender);
do
{
cout << "Height: ";
cin >> height;
invalidHeight = height < 24 || height > 110;
heightOK = ((gender == 'm' || gender == 'M') &&
(height > 65 && height < 80));
heightOK = heightOK || ((gender == 'f' || gender == 'F') &&
(height > 62 && height < 75));
if(invalidHeight)
{
cout << "***** Invalid height; please enter a height in inches between 24 and 110. *****"
<< endl;
}
}while(invalidHeight);
do
{
cout << "Weight: ";
cin >> weight;
invalidWeight = weight < 50 || weight > 1400;
weightOK = ((gender == 'm' || gender == 'M') &&
(weight > 130 && weight < 250));
weightOK = weightOK || ((gender == 'f' || gender == 'F') &&
(weight > 110 && weight < 185));
if(invalidWeight)
{
cout << "***** Invalid weight; please enter a weight in lbs between 50 and 1400."
<< endl;
}
}while(invalidWeight);
if(heightOK && weightOK)
{
cout << "This candidate has been ACCEPTED!" << endl;
validCandidateCount = validCandidateCount + 1;
}
else if (!heightOK)
{
cout << "This candidate has been rejected based on the HEIGHT requirement."
<< endl;
}
else if (!weightOK)
{
cout << "This candidate has been rejected based on the WEIGHT requirement."
<< endl;
}
else if (!(heightOK && weightOK))
{
cout << "This candidate has been rejected based on the HEIGHT and WEIGHT requirements"
<< endl;
}
cout << "Gender: ";
cin>>gender;
cin.ignore (1000,'\n');
}
cout << validCandidateCount << " candidate(s) accepted!" << endl;
percentOutput = (double)validCandidateCount / (double)candidateCount;
cout << "That's " << percentOutput*100 <<"%!" << endl;
return 0;
}
The Boolean data types need to be declared true or false. And this needs to be set before iterations.
Also:
The program needs to run before a user can input x to quit.
std:string QUIT;
QUIT = “XXX”;
Then use selection structure.

Why won't this C++ While loop work? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm simply trying to get the user to put in their name/age and verify if it's correct. If not then they get 4 tries before the program will abort. However my while loops don't loop, instead they just continue on to the next loop. I've tried a variation of things inside the while parenthesis (op != 1) (!(op = 1)) etc.
int main() {
system("Color 0A");
string name;
int age;
int tries = 0;
int op = 0;
cout << "Hello User" << endl;
Sleep(3000);
while ((op != 1) && (tries < 4)) {
name = entName(name);
cout << "So your name is " << name << "?" << endl;
cout << "Enter '1' for YES or '2' for NO. ";
cin >> op;
if (op == 1) {
cout << "Perfect!";
}
if (op == 2) {
cout << "Please Try Again!";
tries+ 1;
}
if (tries = 4) {
//abort the program
}
}
int op2 = 0;
int tries2 = 0;
while ((op2 != 1) && (tries2 < 4)) {
op2 = 3;
age = entAge();
cout << "So you are " << age << " years old?" << endl;
while ((op2 != 1) && (op2 != 2)) {
cout << "Enter '1' for YES or '2' for NO. ";
cin >> op2;
if (op2 == 1) {
cout << "Perfect!\n";
}
if (op2 == 2) {
cout << "Please Try Again!\n";
tries2++;
}
if (tries2 = 4) {
//abort the programhi
}
}
}
return 0;
}
I'm fairly new to C++ so I'm sorry if it does have a simple answer. But anyway, I've been debugging this for over half an hour and I looked online for 20+ minutes.
if (tries = 4) {
//abort the program
}
Change this to
if (tries == 4) {
//abort the program
}
And
f (op == 2) {
cout << "Please Try Again!";
tries+= 1; // tries+ 1;
}
You can increment value in C++ like this tries+ 1;. Either use tries+= 1; or tries++;
tries+ 1; should be tries += 1; or tries++;
And,
if (tries = 4) {
//abort the program
}
should be:
if (tries == 4) {
//abort the program
}
Your program should look like this:
int main()
{
system("Color 0A");
string name;
int age;
int tries = 0;
int op = 0;
cout << "Hello User" << endl;
Sleep(3000);
while ((op != 1) && (tries < 4)) {
name = entName(name);
cout << "So your name is " << name << "?" << endl;
cout << "Enter '1' for YES or '2' for NO. ";
cin >> op;
if (op == 1) {
cout << "Perfect!";
}
if (op == 2) {
cout << "Please Try Again!";
tries+= 1;
}
if (tries == 4) {
//abort the program
}
}
int op2 = 0;
int tries2 = 0;
while ((op2 != 1) && (tries2 < 4)) {
op2 = 3;
age = entAge();
cout << "So you are " << age << " years old?" << endl;
while ((op2 != 1) && (op2 != 2)) {
cout << "Enter '1' for YES or '2' for NO. ";
cin >> op2;
if (op2 == 1) {
cout << "Perfect!\n";
}
if (op2 == 2) {
cout << "Please Try Again!\n";
tries2++;
}
if (tries2 == 4) {
//abort the programhi
}
}
}
You have forget to use = sign at multiple places. tries = 4 should be tries == 4 for comparing variable tries with numeric 4. tries = 4 was reassigning the variable tries to four and your while loop was getting terminated after it's first run. Also, tries + 1 should be tries += 1 or tries++ to increment the value of tries variable by one.

C++ Function being called when it isn't supposed to

I'm nearly finished working on a small guessing game, but i have run into a problem I don't know how to work around.
The problem is with the check_guess function that is checking to make sure the guess being input is a number between 1 and 100.
When running the program the first time, everything works fine.
http://i.imgur.com/pprunDT.png (I would post images if my reputation weren't so low)
But every time after, where yes to play again is chosen, the program runs through the check_guess function and displays "Invalid Input" when it shouldn't
http://i.imgur.com/8OSnSJt.png
I'm not sure why the program is behaving this way.
The code for the entire program is here:
#include <iostream>
#include <cstdlib> //for rand
#include <ctime> //for time
#include <string>
#include <sstream> //for conversions from string to int
using namespace std;
int check_guess(int tries) { //function for limiting the input of guess
string guess = "";
int result = 0;
do {
getline (cin, guess);
istringstream convert(guess);
if ( !(convert >> result) || (result < 1 || result > 100) ) {
result = 0;
cout << "Invalid Input.\n" << endl;
cout << "You have " << tries << " tries: ";
}
} while (result == 0);
return result;
}
bool play_again() { //function for limiting the input of mode
bool quit;
string yn;
do {
cin >> yn;
if ( yn == "y" || yn == "yes" ) {
quit = false;
}
else if ( yn == "n" || yn == "no" ) {
quit = true;
}
else {
yn = "invalid";
cout << "Invalid input.\n\nEnter 'y' or 'n': ";
}
} while ( yn == "invalid" );
return quit;
}
int main()
{
srand(time(0)); //sets seed to be random
int mystery = 0; //defines mystery number
int guess = 0; //defines guess
int tries = 5; //defines trys
bool quit = false; //defines replay or quit
cout << "----------------------------------\n";
do { //while mode is not set to quit, keep playing
tries = 5; //resets tries each new game
mystery = rand() % 100 + 1; //sets mystery number to be random
guess = 0;
cout << "Pick a number between 1 and 100.\n\nYou have 5 tries: ";
while (tries != 0) { //loops until you have no tries left
guess = check_guess(tries);
if (guess == mystery) { tries = 0; } //if you guess right it ends the loop
else { tries--; } //guessing wrong lowers tries by 1
if ( tries != 0 && guess > mystery) {
cout << guess << " is too high.\n" << endl;
cout << "You have " << tries << " tries: ";
}
if ( tries != 0 && guess < mystery) {
cout << guess << " is too low.\n" << endl;
cout << "You have " << tries << " tries: ";
}
}
if (guess == mystery) { //if guess == mystery by time loop ends you win
cout << "Got it! You Win!\n" << endl;
}
else { //if not, you lose
cout << "You Lose! The number was: " << mystery << ".\n" <<endl;
}
cout << "-------------------\n";
cout << "Play Again?(y/n): "; //ask user to play again
quit = play_again();
cout << "-------------------\n";
if (quit == false)
cout << endl;
} while (quit == false);
cout << "----------------------------------" << endl;
return 0;
}
I'm not sure how to fix this.
this line:
cin >> yn;
only reads the 'y' but not the end of line. As a result, the next execution of this instruction
getline (cin, guess);
initializes guess to an empty string.
On line 19, import the code "cin.ignore();" without quotations.
So your code reads as
`int check_guess(int tries) { //function for limiting the input of guess
string guess = "";
int result = 0;
do {
getline (cin, guess);
istringstream convert(guess);
if ( !(convert >> result) || (result < 1 || result > 100) ) {
result = 0;
cin.ignore();
cout << "Invalid Input.\n" << endl;
cout << "You have " << tries << " tries: ";
}
} while (result == 0);
return result;
}
`
and so on. This stops input into the console briefly. You're code is reading the 'y' to try again as the input for the number when you restart as well. Putting in the little line cin.ignore(), stops it from inputting y twice.
Change play_again() to:
bool play_again() { //function for limiting the input of mode
bool quit;
string yn;
do {
getline (cin, yn);
if ( yn == "y" || yn == "yes" ) {
quit = false;
}
else if ( yn == "n" || yn == "no" ) {
quit = true;
}
else {
yn = "invalid";
cout << "Invalid input.\n\nEnter 'y' or 'n': ";
}
} while ( yn == "invalid" );
return quit;
}

C++ Cout & Cin & System "Ambiguous" [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I was just programming in c++, when all of a sudden all the "cout"s and "cin"s were errors and "Ambiguous". Including System.
I don't know why this happened. Everything was fine, I was coding the same program for about 2 hours, when it just... happened.
EDIT
I can still run the program without errors, but they show as errors on the text, the red scribbly line. What happened?
I'm using the Visual Studio 2013 IDE, whatever it comes with.
#include <iostream>
#include <ctime>
#include <string>
#include <Windows.h>
#include <cstdlib>
#include <stdlib.h>
using namespace std;
int main()
{
struct Gun
{
string name;
int damage;
int cost;
bool purchased;
bool equipped;
} M4A1, FAMAS;
//WEAPONS INFO
M4A1.cost = 50;
M4A1.damage = 5;
M4A1.purchased = false;
M4A1.equipped = false;
FAMAS.cost = 300;
FAMAS.damage = 10;
FAMAS.purchased = false;
FAMAS.equipped = false;
//WEAPONS INFO
//-----PLAYER(BEGIN)-----
struct Player
{
int health;
string name;
int money;
int energy;
string l_a;
string r_a;
string l_l;
string r_l;
string rank;
} Player;
//GAME PLAYER BEGIN
Player.l_a = "Normal";
Player.r_a = "Normal";
Player.l_l = "Normal";
Player.r_l = "Normal";
Player.health = 100;
Player.money = 100;
Player.energy = 100;
string plyrname;
string rank = "Private";
Player.name = plyrname;
//GAME PLAYER END
//-----PLAYER(END)-----
cout << "What is your name? ";
cin >> plyrname;
goto mmenu;
mmenu:
//-----MAIN MENU(BEGIN)-----
system("CLS");
if (Player.l_a == "Damaged")
{
cout << "Your Left Arm is damaged! Sleep for a while to fix it!";
Sleep(1600);
}
if (Player.r_a == "Damaged")
{
cout << "Your Right Arm is damaged! Sleep for a while to fix it!";
Sleep(1600);
}
if (Player.l_l == "Damaged")
{
cout << "Your Left Leg is damaged! Sleep for a while to fix it!";
Sleep(1600);
}
if (Player.r_l == "Damaged")
{
cout << "Your Right Leg is damaged! Sleep for a while to fix it!";
Sleep(1600);
}
if (Player.money >= 500 && Player.rank == "Private")
{
system("CLS");
cout << "You have been promoted to Private 2!";
Player.rank = "Private 2";
Sleep(1600);
}
if (Player.money >= 1000 && Player.rank == "Private 2")
{
system("CLS");
cout << "You have been promoted to Private First Class!";
Player.rank = "Private First Class";
Sleep(1600);
}
system("CLS");
cout << "Health: " << Player.health << ". Money: " << Player.money << " dollars." << " Energy: " << Player.energy;
if (M4A1.equipped)
cout << "\nGun: M4A1";
if (FAMAS.equipped)
cout << "\nGun: FAMAS";
cout << "\n\nRank: " << Player.rank;
cout << "\n\n1) Go to Gunstore\n2) Sleep\n3) Fight\n\nAction: ";
int mmenuch1;
cin >> mmenuch1;
if (mmenuch1 == 1)
{
goto gunstore;
}
if (mmenuch1 == 2)
{
system("CLS");
cout << "You sleep, restoring your energy.";
Player.energy = 100;
if (Player.l_a == "Damaged")
{
cout << "\n\nYour Left Arm was healed.";
Player.l_a = "Normal";
}
if (Player.r_a == "Damaged")
{
cout << "\n\nYour Right Arm was healed.";
Player.r_a = "Normal";
}
if (Player.l_l == "Damaged")
{
cout << "\n\nYour Left Leg was healed.";
Player.l_l = "Normal";
}
if (Player.r_l == "Damaged")
{
cout << "Your Right Leg was healed.";
}
Sleep(1400);
goto mmenu;
}
if (mmenuch1 == 3)
{
system("CLS");
goto fight;
}
//-----MAIN MENU(END)-----
fight:
srand(time(0));
system("CLS");
if (Player.r_a == "Damaged" || Player.r_l == "Damaged" || Player.l_a == "Damaged" || Player.l_l == "Damaged")
{
cout << "You're injured, sleep to heal.";
Sleep(1400);
goto mmenu;
}
if (Player.energy < 40)
{
cout << "You don't have enough energy to fight.";
Sleep(1400);
goto mmenu;
}
if (M4A1.equipped == false && FAMAS.equipped == false)
{
cout << "You don't have a gun equipped.";
Sleep(1400);
goto gunstore;
}
if (M4A1.equipped == true && Player.energy > 40)
{
int randnum1 = rand() % (M4A1.damage - 2 + 1) + 2;
Player.money = Player.money + (randnum1 * 15);
Player.energy = Player.energy - 40;
int randnum3 = rand() % (10 - 1 + 1) + 1;
if (randnum3 < 4)
{
int randnum4 = rand() % (13 - 1 + 1) + 1;
if (randnum4 < 3)
{
Player.l_a = "Damaged";
}
if (randnum4 <= 6 && randnum4 >= 4)
{
Player.r_a = "Damaged";
}
if (randnum4 <= 9 && randnum4 >= 7)
{
Player.l_l = "Damaged";
}
if (randnum4 <= 13 && randnum4 >= 10)
{
Player.r_l = "Damaged";
}
}
cout << "You fight, killing " << randnum1 << " enemies, making " << randnum1 * 15 << " dollars!";
Sleep(1600);
goto mmenu;
}
if (FAMAS.equipped == true && Player.energy > 40)
{
int randnum2 = rand() % (FAMAS.damage - 4 + 1) + 4;
Player.money = Player.money + (randnum2 * 15);
Player.energy = Player.energy - 40;
int randnum5 = rand() % (10 - 1 + 1) + 1;
if (randnum5 < 4)
{
int randnum6 = rand() % (13 - 1 + 1) + 1;
if (randnum6 < 3)
{
Player.l_a = "Damaged";
}
if (randnum6 <= 6 && randnum6 >= 4)
{
Player.r_a = "Damaged";
}
if (randnum6 <= 9 && randnum6 >= 7)
{
Player.l_l = "Damaged";
}
if (randnum6 <= 13 && randnum6 >= 10)
{
Player.r_l = "Damaged";
}
}
cout << "You fight, killing " << randnum2 << " enemies, making " << randnum2 * 15 << " dollars!";
Sleep(1600);
goto mmenu;
}
//-----GUNSTORE(BEGIN)-----
gunstore:
system("CLS");
cout << "Welcome to the gunstore! You have " << Player.money << " dollars.";
cout << "\n\n1)M4A1 | Assault Rifle | $50\n2)FAMAS | Assault Rifle | $300\n\n3)Back\n\nAction: ";
int gschoice1;
cin >> gschoice1;
if (gschoice1 == 1)
{
goto prchs_M4A1;
}
else if (gschoice1 == 2)
{
goto prchs_FAMAS;
}
else if (gschoice1 == 3)
{
goto mmenu;
}
prchs_M4A1:
system("CLS");
if (M4A1.purchased == true)
{
cout << "You already purchased the M4A1. Would you like to equip it?\n\n1)Yes\n2)No\n\nAction: ";
int gschoice6;
cin >> gschoice6;
if (gschoice6 == 1)
{
system("CLS");
M4A1.equipped = true;
FAMAS.equipped = false;
goto mmenu;
}
else if (gschoice6 == 2)
{
goto gunstore;
}
}
if (Player.money >= 0)
{
system("CLS");
cout << "Would you like to buy the M4A1?";
cout << "\n\n1)Yes\n2)No\n\nAction: ";
int gschoice2;
cin >> gschoice2;
if (gschoice2 == 1)
{
system("CLS");
Player.money = Player.money - M4A1.cost;
M4A1.purchased = true;
cout << "You've purchased the M4A1. Would you like to equip it?\n\n1)Yes\n2)No\n\nAction: ";
int gschoice3;
cin >> gschoice3;
if (gschoice3 == 1)
{
system("CLS");
M4A1.equipped = true;
FAMAS.equipped = false;
cout << "You've equipped the M4A1";
Sleep(1400);
goto gunstore;
}
if (gschoice3 == 2)
{
system("CLS");
M4A1.equipped = false;
goto gunstore;
}
}
if (gschoice2 == 2)
{
system("CLS");
goto gunstore;
}
}
else if (Player.money < 0)
{
system("CLS");
cout << "You don't have enough money.";
Sleep(1400);
goto gunstore;
}
prchs_FAMAS:
if (FAMAS.purchased == true)
{
cout << "You already purchased the FAMAS. Would you like to equip it?\n\n1)Yes\n2)No\n\nAction: ";
int gschoice7;
cin >> gschoice7;
if (gschoice7 == 1)
{
system("CLS");
FAMAS.equipped = true;
M4A1.equipped = false;
goto mmenu;
}
else if (gschoice7 == 2)
{
goto gunstore;
}
}
if (Player.money >= 100)
{
system("CLS");
cout << "Would you like to buy the FAMAS?";
cout << "\n\n1)Yes\n2)No\n\nAction: ";
int gschoice4;
cin >> gschoice4;
if (gschoice4 == 1)
{
system("CLS");
Player.money = Player.money - FAMAS.cost;
FAMAS.purchased = true;
cout << "You've purchased the FAMAS. Would you like to equip it?\n\n1)Yes\n2)No\n\nAction: ";
int gschoice5;
cin >> gschoice5;
if (gschoice5 == 1)
{
system("CLS");
FAMAS.equipped = true;
M4A1.equipped = false;
cout << "You've equipped the FAMAS";
Sleep(1400);
goto gunstore;
}
if (gschoice5 == 2)
{
system("CLS");
FAMAS.equipped = false;
goto gunstore;
}
}
if (gschoice4 == 2)
{
system("CLS");
goto gunstore;
}
}
else if (Player.money < 100)
{
system("CLS");
cout << "You don't have enough money.";
Sleep(1400);
goto gunstore;
}
//-----GUNSTORE-----
}
This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.
Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.
In this case I'd ask why you're including both cstdlib and stdlib.h; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib puts them in the namespace std in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!
Anyway, your use of using namespace std (which I would recommend against, in future) means that std::system from cstdlib now conflicts with system from stdlib.h. I can't explain what's going on with std::cout and std::cin.
Try removing #include <stdlib.h> and see what happens.
If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.