当我在 C++ 中使用以下代码时,我得到一个无限循环,我不明白为什么。我怀疑问题出在input_words()
函数内。这是代码:
#include<iostream>
using namespace std;
string input_words(int maxWords) {
int nWord = 0;
string words[maxWords];
string aWord = "";
while (aWord != "Quit" && nWord < maxWords) {
cout << "Enter a number ('Quit' to stop): ";
getline (cin, aWord);
words[nWord] = aWord;
nWord++;
}
return *words;
}
int num_words (string words[], int maxWords) {
int numWords = 0;
for (int i=0; i<maxWords; i++) {
if (words[i] == "Quit") {
break;
}
numWords++;
}
return numWords;
}
int main() {
const int MAX_WORDS = 100;
string words[MAX_WORDS] = input_words(MAX_WORDS);
int lenWords = num_words(words, MAX_WORDS);
cout << "\nThere are " << lenWords << " words:\n";
for (int i=0; i<MAX_WORDS; i++) {
if (words[i] == "Quit") {
break;
}
cout << words[i] << "\n";
}
return 0;
}
更具体地说,即使在提示输入单词时键入“退出”,我也无法退出。我怎么能解决这个问题?我知道这是菜鸟代码 :) 我刚开始使用 C++