Alpha Reaper
Alpha Reaper

Reputation: 19

How do I make the code not repeat

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.

Upvotes: 1

Views: 118

Answers (4)

mammothb
mammothb

Reputation: 16

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;
}

Upvotes: 0

JakeWebbDev
JakeWebbDev

Reputation: 11

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.

Upvotes: 1

user9735518
user9735518

Reputation:

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)

Upvotes: 6

retinotop
retinotop

Reputation: 483

You could also try out something like that.

char i;

while((std::cin >> i) && i != '1') {
    .... 
}

Upvotes: 0

Related Questions