I've written a short program to check words entered against a list of words in a seperate text file by reading the file into an array and then comparing the word entered against each element. It works fine when a real word is entered, but I can't work out how to output "This is not a word" just once when the input doesn't match the array, rather than it performing the output for every element. I assume I need a break in there somewhere but any help would be great.
The way this looks is you're checking an entered word against a list of predetermined words, and on each predetermined word you decide whether or not the entered word matches. What if I enter a word that is halfway down your list? The program is going to say it's not a word about 17000 times until it hits the match. Alter this so it doesn't output anything until it either finds a match, or it reaches the end of your array and has not yet found a match.
Having taken out the else statement, the program runs fine when a word is entered. I'm not sure how to make it wait until its made it through the whole array before outputting though. I've tried putting breaks both inside and outside the if statement but that didn't help. Any advice?
There are several ways. The method below checks the ending value of i in the for loop.
1 2 3 4 5 6 7 8 9 10
int i = 0;// expanding scope
for(i=0; i<357386; i++) {
if((array[i].compare(x)) == 0) {
cout << "This is a word.";
break;// i will stop increasing now
}
}
// check if i reached the terminal value in the for loop
if( i==357386 ) cout << "This is not a word";//
350k isn't really a huge number for modern PCs, but it is getting up there and a BST would cut down drastically on your average search time. A linear search is going to be magnitudes longer.