I get an infinite loop when I use the following code in C++ and I don’t understand why. I suspect the problem is within the input_words() function. Here is the code:
#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;
}
More specifically, I can’t exit even when I type ‘Quit’ when prompted for a word. How could I solve this? I know this is noob code 🙂 I’m just starting on C++
I modified the function in such a way:
After inputting Quit, it prints “finished”, and then “started” again.
Your code is calling the function several times.
The problem is that the function returns only one string. so the line
seems to call the function input_words
MAX_WORDStimes.A good way would be to switch to
vector<string>: