c++ - 为什么我的代码在 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++ 很陌生,所以如果这不是一个好问题,我很抱歉。
解决方案
我对你的代码做了一些更正。
- 最后用大括号添加了 return 0。
- 将 /n 替换为 \n 。(在此上下文中无关但很重要。)
- 一旦在 else 语句中获取新输入,就将 n 的值重置为零。由于您没有将 n 的值重置为零,因此如果第一次尝试输入无效(正如您在代码中所说),您将收到错误消息。
#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;
}
希望对您有所帮助。如果您无法理解,请在评论中告诉我。
推荐阅读
- javascript - 尝试关闭并打开命令 quick.db
- twilio - Twilio - 如果我们有用户凭据,如何将用户直接导航到流编辑页面
- c# - 带有数字的希伯来字符串 concat 导致顺序错误
- php - 如何使用php rand fucuction生成2组匹配的数据
- python - 如何使用单个表单更新多个模型
- web-services - 在 Flutter 的 SOAP 请求中传递字符串列表
- python - 如何使用 Django 在 Python 中查看我的 HTML 页面
- python - 指数小于 1 的 pytorch 数学返回 nan
- python - 如何确定 skimage.filter.gabor 函数的频率?
- c - 是什么导致“警告:来自不兼容的指针类型错误的赋值”?