首页 > 解决方案 > 为什么我的代码在 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++ 很陌生,所以如果这不是一个好问题,我很抱歉。

标签: c++loopsif-statementwhile-loop

解决方案


我对你的代码做了一些更正。

  • 最后用大括号添加了 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;
}

希望对您有所帮助。如果您无法理解,请在评论中告诉我。


推荐阅读