如何使代码不重复

时间:2018-05-03 14:19:26

标签: c++

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

当我输入升级然后输入除变量&#34; 1&#34;以外的任何其他内容时,代码将无限重复。

4 个答案:

答案 0 :(得分:6)

这是一个永无止境的问题 请参阅此问题:Infinite loop with cin when typing string while a number is expected

我认为您的代码存在一些错误。

int upgr;
cin >> upgr; // you can type any number you want (-2 147 483 648   /   2 147 483 647)

我建议您在阅读一行时使用getlinecin.getlinefgets代替cin >>

只需使用while(1)while(true)

即可

答案 1 :(得分:1)

您通过永远不会更改“1”变量的值来创建无限循环。在某种程度上,您需要在迭代条件时更改该值,否则您将永远不会退出循环。

答案 2 :(得分:0)

你也可以试试这样的东西。

char i;

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

答案 3 :(得分:0)

在您的代码中,while (1 == 1)会创建一个无限循环。由于我假设您希望此代码在他们决定停止之前不断询问玩家他们的输入,您可以添加一个选项exit,当玩家想要时它会突破循环。

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