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;
}
具体的には、単語の入力を求められたときに「Quit」と入力しても終了できません。どうすればこれを解決できますか?私はこれがnoobコードであることを知っています:)私はC ++を始めたばかりです