大佬教程收集整理的这篇文章主要介绍了为什么我的代码在 C++ 中运行“while 循环”时会导致问题?在 if else 语句中,它不断地打印错误的输出,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
#include <iostream>
#include <String>
#include <cString>
using namespace std;
int main() //geTing input part
{
String wanteDWord,name1,name2;
cout<<"Player one,please enter your name: ";
cin >> name1;
cout<<"Player two,please enter your name: ";
cin >> name2;
cout << "OK " << name1 << " and "<< name2<<". Let's start the game!/n";
cout << name1 << ",please input the word you want " << name2 << "to guess: ";
cin >> wanteDWord;
// find the leght of the word
int len = wanteDWord.size();
// check whether the String is Alphabetical or not
char w; // w = the charater on that specific index
int n = 0; // n = index
while ( n < len && n >= 0)
{
w = wanteDWord[n];
if ((int(w) >= 65 && int(w) <= 90) || ( int(w) >= 97 && int(w) <= 122))
{
n += 1;
cout << w << endl;
}
else
{
cout << "InvalID word! Try again." << endl; //this gives me an infinite loop why?
cout << name1 << ",please input the word you want " << name2 << "to guess: ";
cin >> wanteDWord;
}
}
}
我的问题在于“// 检查字符串是否按字母顺序排列”部分。当我输入“CS201”作为无效输入时,它起初工作正常并要求我输入另一个单词。但后来我输入了一个有效的词,例如“香蕉”,但它再次显示“无效的词!再试一次。”当它应该接受输入为有效时。为什么我收到这个错误?我对 C++ 很陌生,所以如果这不是一个好问题,那么抱歉。
我对您的代码做了一些更正。
#include <iostream>
#include <String>
#include <cString>
using namespace std;
int main() //geTing input part
{
String wantedWord,name1,name2;
cout << "Player one,please enter your name: ";
cin >> name1;
cout << "Player two,please enter your name: ";
cin >> name2;
cout << "OK " << name1 << " and " << name2 << ". Let's start the game!\n";
cout << name1 << ",please input the word you want " << name2 << "to guess: ";
cin >> wantedWord;
// find the leght of the word
int len = wantedWord.size();
// check whether the String is alphabetical or not
char w; // w = the charater on that specific index
int n = 0; // n = index
while (n < len && n >= 0)
{
w = wantedWord[n];
if ((int(w) >= 65 && int(w) <= 90) || (int(w) >= 97 && int(w) <= 122))
{
n ++;
cout << w << endl;
}
else
{
cout << "Invalid word! Try again." << endl; //this gives me an infinite loop why?
cout << name1 << ",please input the word you want " << name2 << "to guess: ";
cin >> wantedWord;
n=0;
}
}
return 0;
}
希望对你有帮助。如果您无法理解,请在评论中告诉我。
以上是大佬教程为你收集整理的为什么我的代码在 C++ 中运行“while 循环”时会导致问题?在 if else 语句中,它不断地打印错误的输出全部内容,希望文章能够帮你解决为什么我的代码在 C++ 中运行“while 循环”时会导致问题?在 if else 语句中,它不断地打印错误的输出所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。