int main() {
power=1;
while (1 == 1){
tapcost=power*3;
cout << "type upgrade/buy/a" << endl;
cin >> way;
if (way == "upgrade"){
cout << "1. A Power " << "(Costs: " << tapcost << ")" << endl;
cin >> upgr;
if (upgr == 1){
if (0<=money-power*3){
power=power+1;
money=money-power*3;
}
else
cout << "You can't afford that!!!" << endl;
}
}
if (way == "a"){
money=money+power;
}
}
return 0;
}
When I type upgrade and then type anything else other than the variable "1", the code will repeat infinitely.
This is a never-ending problem.
See this question: Infinite loop with cin when typing string while a number is expected
I think your code have some mistakes.
int upgr;
cin >> upgr; // you can type any number you want (-2 147 483 648 / 2 147 483 647)
I suggest you to use getline, cin.getline or fgets instead of cin >> when reading a line.
And just use while(1) or while(true)
You have created an infinite loop by never changing the value of your ‘1’ variable. In some way you need to change that value when iterating through your conditions or else you’ll never get out of your loop.
You could also try out something like that.
char i;
while((std::cin >> i) && i != '1') {
....
}
In your code, while (1 == 1) creates an infinite loop. Since I assume you want this code to keep asking players for their input until they decide to stop, you can add an option exit which breaks out of the loop when the player wants to.
#include <iostream>
int main() {
int power = 1;
int money = 1000;
while (1 == 1) {
int tapcost = power * 3;
std::string way;
std::cout << "type upgrade/buy/a/exit" << std::endl;
std::cin >> way;
if (way == "upgrade") {
std::cout << "1. A Power " << "(Costs: " << tapcost << ")" << std::endl;
int upgr;
std::cin >> upgr;
if (upgr == 1) {
if (0 <= money - power * 3) {
power = power + 1;
money = money - power * 3;
}
else {
std::cout << "You can't afford that!!!" << std::endl;
}
}
}
if (way == "a") {
money = money + power;
}
if (way == "exit") {
break;
}
}
return 0;
}
Related
I wanted to use only 1 and 0 for the binary. But instead the answer keep giving me the 2nd option with whatever number I typed. I had tried where did I programmed wrongly but unfortunately I still can't find it. So I hoped that I could get some help here.
#include<iostream>
#include<cmath>
using namespace std;
int DualzahlZuDezimal(long long n)
{
int dez = 0;
int i = 0, rem;
while (n != 0)
{
rem = n % 10;
n /= 10;
dez += rem * pow(2, i);
++i;
}
return dez;
}
string a;
int main()
{
long long n;
int dez;
cout << "Test Ein- und Ausgabe : \n";
cout << "----------------------- \n";
cout << "Eingabe einer Dualzahl : ";
cin >> n;
if ((n == '1') && (n == '0'))
{
cout << "Dual : " << n << endl;
cout << "Dezimal : " << DualzahlZuDezimal(n) << endl;
cout << "cin ok ? : ja-ok" << endl;
return 0;
}
else
{
cout << "Dual : 0" << endl;
cout << "Dezimal : 0" << endl;
cout << "cin ok ? : nein-nicht ok" << endl;
return 0;
}
}
If I understand this right, you want the user to enter a binary number, like 10001101001, and you will show the decimal equivalent (1129 in this case).
There are 2 general ways to do that yourself:
You can read the value as a number, as you do, and then apply your conversion
process, except that you check that rem is either 0 (in which case you do
nothing), or 1 (in which case you add the power of 2). If it's another value,
you report the error, and return 0.
You can read the value as a std::string instead. Then you can use
std::find_first_not_of()
to check for contents other than 0 or 1:
if (n.find_first_not_of("01") != string::npos) { /* complain */ }
but then you need to do the conversion based on characters.
But the best approach is not to reinvent the wheel and instead let the standard library handle it for you via stol():
#include <cstddef>
#include <iostream>
#include <string>
using namespace std;
int
main()
{
string text;
cout << "Enter a binary number: " << flush;
cin >> text;
size_t endpos = 0;
long decimal_number = stol(text, &endpos, 2); // base 2 == binary
if (endpos != text.size()) {
cerr << "'" << text << "' is not a valid binary number!" << endl;
return 1;
}
else {
cerr << "binary number: " << text << endl;
cerr << "decimal number: " << decimal_number << endl;
return 0;
}
}
Keep in mind that input from the console is text. If you need to check that the text matches a particular format (in this case, consists entirely of 1's and 0's), the simplest approach is to look at that text:
std::string input;
std::cin >> input;
bool input_is_valid = true;
for (int i = 0; input_is_valid && i < input.length(); ++i) {
if (input[i] != '0' && input[i] != '1')
input_is_valid = false;
}
then, if the input is valid, convert the text to a numeric value:
long long n = std::stoll(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');
}
}
So, I'm super new to C++ and am sharing a book with a friend. I'm creating a simple guessing game, where the user imagines a number, and the computer attempts to guess it. When I debug in Visual Studio, the project does make a guess, and properly prints "how did I do?". At this point, it should get user input for the 'feedback' variable. After the prompt, however, it seems as if it will only repeat everything before the 'while' statement. Does the problem concern the feedback char variable (maybe I should've just used 'cin' and integers?), or am I just missing something really obvious?
//Game that attempts to guess a number from one to twenty.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
auto lowbound = 1;
auto highbound = 20;
auto guess = 10;
auto gamecont = true;
char feedback[1];
cout << " Pick a number from one to twenty in you head and I'll guess it; no cheating!" << endl << endl;
cout << " If my guess is too low, just say (1). If too high, say (2). Say (3) if I've got it. It's (ENTER) to get going!" << endl << endl;
cout << " Waiting on you..." << endl << " ";
cin.get();
while(gamecont)
{
cout << " I'm thinking your number is " << guess << "." << endl << endl;
cout << " How did I do?" << endl << endl << " ";
cin.get(feedback, 1);
if (feedback[1] == 1) // The guess was too low.
{
if (guess == 10)
{
guess = 15;
}
else if (guess >= 15)
{
guess++;
}
else if (guess < 10)
{
guess++;
}
}
else if (feedback[1] == 2) // The guess was too high.
{
if (guess == 10)
{
guess = 5;
}
else if (guess <= 5)
{
guess--;
}
else if (guess > 10)
{
guess--;
}
}
else if (feedback[1] == 3) // The guess was correct.
{
gamecont = false;
}
}
return 0;
}
Sorry if this question is stupid for whatever reason, and thanks in advance for reading.
a journey of a thousand miles begins with a single step, so here´s some aid for your first step:
using namespace std;
don´t do that. std:: is crowded with identifiers you might use too, problems are guaranteed.
char feedback[1];
You´ll never have input longer than 1, so
char feedback;
is more than appropriate. (besides: arrays are 0 based so it should have been char feedback[0]; instead of char feedback[1];)
cout << " Pick a number from one to twenty in you head and I'll guess it; no cheating!" << endl << endl;
std::endl flushes the buffer, no need to do that twice. Simply use '\n':
std::cout << " Pick a number from one to twenty in you head and I'll guess it; no cheating!" << "\n\n";
you´ll get the character code of the key in feedback. '1' is not equal to 1, so
if (feedback == 1)
should be
if (feedback == '1')
Thats it. There still some work remaining to do for you, e.g. the guessing strategy is poor, but that should be a start.
//Game that attempts to guess a number from one to twenty.
#include <iostream>
int main()
{
auto lowbound = 1;
auto highbound = 20;
auto guess = 10;
auto gamecont = true;
char feedback;
std::cout << " Pick a number from one to twenty in you head and I'll guess it; no cheating!" << "\n\n";
std::cout << " If my guess is too low, just say (1). If too high, say (2). Say (3) if I've got it. It's (ENTER) to get going!" << "\n\n";
std::cout << " Waiting on you..." << "\n\n";
std::cin.get();
while(gamecont)
{
std::cout << " I'm thinking your number is " << guess << "." << "\n\n";
std::cout << " How did I do?" << "\n\n";
std::cin.ignore();
std::cin.get(feedback);
if (feedback == '1') // The guess was too low.
{
if (guess == 10)
{
guess = 15;
}
else if (guess >= 15)
{
guess++;
}
else if (guess < 10)
{
guess++;
}
}
else if (feedback == '2') // The guess was too high.
{
if (guess == 10)
{
guess = 5;
}
else if (guess <= 5)
{
guess--;
}
else if (guess > 10)
{
guess--;
}
}
else if (feedback == '3') // The guess was correct.
{
gamecont = false;
}
}
return 0;
}
I'm trying to get the program to loop again, up to three times, if the user entered a number that does not follow the function defined in the if statement. The code as is, only loops once and then exits. Did I type the for loop incorrectly or is it the if...else statement that is wrong?
#include <iostream>
using std::cout; using std::cin; using std::endl;
int main() {
cout << "Enter a positive odd number less than 40: ";
int num = 0;
for (int a = 0; a < 3; ++a);
cin >> num;
{
if (num < 40 && num > 0 && num % 2 == 1)
{
cout << "Thank you!" << endl;
}
else cout << "That is incorrect, try again!" << endl;
}
}
Did I type the for loop incorrectly or is it the if...else statement that is wrong?
Both. You should (1) remove the semicolon following the for statment; (2) move cin >> num into the for loop body; (3) add break; inside the if.
for (int a = 0; a < 3; ++a)
{
cin >> num;
if (num < 40 && num > 0 && num % 2 == 1)
{
cout << "Thank you!" << endl;
break;
}
else cout << "That is incorrect, try again!" << endl;
}
BTW1: Try to use the debugger, then you'll find out what happened in fact.
BTW2: The code will fail when cin >> num fails (e.g. user entered an invalid value), you might need to check the result of cin >> num, to process the case. Such as:
for (int a = 0; a < 3; ++a)
{
if (cin >> num)
{
if (num < 40 && num > 0 && num % 2 == 1)
{
cout << "Thank you!" << endl;
break;
}
else cout << "That is incorrect, try again!" << endl;
}
else
{
cin.clear(); // unset failbit
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skip bad input
cout << "Wrong input, try again!" << endl;
}
}
bool isValid = false;
int num;
while(!isValid)
{
cout << "enter a positive odd integer " << endl;
cin >> num;
if(num < 40 && num > 0 && num % 2 == 1 )
{
cout << "thank you"<<endl;
isValid = true;
}
else
isValid = false;
}
Why not use some thing like this, it will loop until isValid = true which will only happen when your conditions are met?
I understand I guess, if you're doing a school project or some thing and you're forced to do it with a for loop but in general this would be a much better solution for some thing like this than a for loop!
I am a newby at this and am working on my fist if/else program. I am having trouble getting the first if statement to recognize my input of "r". I tried playing with just one statement at a time I was able to input all the examples of input the teacher gave us with the desired output for residential and business. However when I run the program altogether I have a problem. I select R for residential, 0 for additional connections, 0 for premium channels and instead of output of $18.50 I get the business fee of $75.00. I am sure it is a simple mistake but I can't figure out what I am doing wrong. Can someone who knows how to work an if/else give me some insight on this!
#include "stdafx.h"
#include <conio.h>
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const float BASIC_RESIDENTIAL = 18.50;
const float BASIC_BUSINESS = 75.00;
const float CONNECT_RESIDENTIAL = 6.50;
const float CONNECT_BUSINESS = 5.00;
const float PREMIUM_RESIDENTIAL = 7.50;
const float PREMIUM_BUSINESS = 50.00;
char customerType;
int numOfConnections;
int numOfPremiumChannels;
float amountCableBill;
cout << fixed << setprecision(2);
cout << "Residential or Business [R or B]? ";
cin >> customerType;
cout << endl << endl;
cout << "How many Additional Connections? ";
cin >> numOfConnections;
cout << endl << endl;
cout << "Total number of Premium Channels: ";
cin >> numOfPremiumChannels;
cout << endl << endl;
if (customerType == 'R' || customerType == 'r')
{
amountCableBill = BASIC_RESIDENTIAL + CONNECT_RESIDENTIAL * numOfConnections + PREMIUM_RESIDENTIAL * numOfPremiumChannels;
}
//else customerType == 'B' || customerType == 'b'; // unnecessary
{
if (numOfConnections <= 9)
amountCableBill = BASIC_BUSINESS + PREMIUM_BUSINESS * numOfPremiumChannels;
else
amountCableBill = BASIC_BUSINESS + (numOfConnections - 9) * CONNECT_BUSINESS + PREMIUM_BUSINESS *numOfPremiumChannels;
}
cout << "Total amount of Cable Bill: " << amountCableBill << endl << endl;
cout << "Press <ENTER> to end..." << endl;
_getch();
return 0;
}
While the condition else if (customerType == 'B' ...) may be redundant, you still have to put an else before the opening brace of the branch.
It's
if (condition) { code } else { code }
You need else in the condition (unless you want "some other code" to be executed every time)
if (customerType == 'R' || customerType == 'r')
{
//Some Code
}
else //<--Notice else
{
//Some other code.
}