I'm having trouble where a user cannot use the same word after input. Below is the snippet of a Boggle program I'm working on.
The code below does not work the way I want it to if for example:
(1)The user inputs the word: fun --> store into temp[0] --> increment count
(2)The user inputs the word: fun --> repeat while loop input for another different input
(3)The user inputs the word: bye --> break while loop --> store into temp[1] --> increment count
(4)The user inputs the word: bye or fun --> will repeat for another input
(5)The user inputs the word: good --> store into temp[2] --> increment count
(6)The user inputs the word: bye --> repeat while loop for another input,
(7)The user inputs the word: fun --> While loop breaks and the word becomes VALID.
You see.. the problem is that it doesn't loop through back to temp[0] to find the word fun again to say its invalid.
Any assistance with this would be appreciated.
//seconds is used with time library, but just ignore its declaration
while (seconds < 300){
string word;
string temp[100];
int count = 0;
cout << "Enter:" << endl;
cin >> word;
for (int i = 0; i < count; i++){
while (word == temp[i]){
cout << "Word was already used. Please type another word." << endl;
cin >> word;
}
}
temp[count] = word;
count = count + 1;
if (seconds >= 300)
break;
}
答案 0 :(得分:1)
试试这个:
string word;
string temp[100];
int count = 0;
cout << "Enter:" << endl;
bool found;
do
{
cin >> word;
found = false;
for (int i = 0; i < count; i++)
{
if (temp[i] == word)
{
found = true;
cout << "Word was already used. Please type another word." << endl;
break;
}
}
}
while (found);
temp[count++] = word;
如果在word
中的任何位置找到temp
,它将会询问一个新单词,然后每次都重新检查整个temp
数组。您的原始代码没有这样做,并且只检查当前索引i
,即使在请求新输入时也是如此。