C++ while循环内嵌套if语句始终触发首个wisdom判断分支问题求助
你的代码问题出在条件判断语法错误,以及逻辑结构设计不合理两方面:
- 第一,所有形如
choice == "wisdom" || "Wisdom"的判断逻辑都不符合C语法规则。在C中,逻辑或运算符||两侧的表达式会分别求值,字符串字面量(比如"Wisdom")会被隐式转换为布尔值:非空指针的取值为true,因此不管choice的实际输入是什么,这类条件判断的结果永远为true。这就导致第一个wisdom相关的判断永远触发,直接赋值后执行continue跳过后续所有逻辑,表现出来就是不管输入什么都只会给wisdom赋值。 - 第二,你当前的逻辑结构存在设计问题:只要第一个wisdom的条件触发,就会执行
continue,就算你修正了条件判断的语法,后续其他属性的判断代码也永远不会被执行。同时最外层的输入合法性判断也因为同样的条件语法错误永远为true,不会触发输入非法的提示。
修正后的参考代码
while (charisma == 0 || strength == 0 || dexterity == 0 || intelligence == 0 || wisdom == 0 || consitution == 0) { cout << "Where would you like to assign your roll of " << statRollArray[chooseStatNumber] << "?" << endl; if (dexterity == 0) { cout << "Dexterity"; } if (intelligence == 0) { cout << " Intelligence"; } if (strength == 0) { cout << " Strength"; } if (wisdom == 0) { cout << " Wisdom"; } if (charisma == 0) { cout << " Charisma"; } if (consitution == 0) { cout << " Constitution" << endl; } string choice = ""; cin >> choice; // 先判断输入是否合法 bool validChoice = false; if (choice == "wisdom" || choice == "Wisdom") { validChoice = true; if (wisdom == 0) { wisdom = statRollArray[chooseStatNumber]; chooseStatNumber += 1; } else { cout << "Wisdom already has been assigned!" << endl; } } else if (choice == "Dexterity" || choice == "dexterity") { validChoice = true; if (dexterity == 0) { dexterity = statRollArray[chooseStatNumber]; chooseStatNumber += 1; } else { cout << "Dexterity already has been assigned!" << endl; } } else if (choice == "strength" || choice == "Strength") { validChoice = true; if (strength == 0) { strength = statRollArray[chooseStatNumber]; chooseStatNumber += 1; } else { cout << "Strength already has been assigned!" << endl; } } else if (choice == "intelligence" || choice == "Intelligence") { validChoice = true; if (intelligence == 0) { intelligence = statRollArray[chooseStatNumber]; chooseStatNumber += 1; } else { cout << "Intelligence already has been assigned!" << endl; } } else if (choice == "charisma" || choice == "Charisma") { validChoice = true; if (charisma == 0) { charisma = statRollArray[chooseStatNumber]; chooseStatNumber += 1; } else { cout << "Charisma already has been assigned!" << endl; } } else if (choice == "constitution" || choice == "Constitution") { validChoice = true; if (consitution == 0) { consitution = statRollArray[chooseStatNumber]; chooseStatNumber += 1; } else { cout << "Constitution already has been assigned!" << endl; } } if (!validChoice) { cout << "Please choose one of the listed stats." << endl; } }
内容的提问来源于stack exchange,提问作者Isaac Orgill
相关产品推荐
相关产品推荐

