Goal: Android/iOS app that displays tricky-to-spell words when user puts in a letter.
The code runs correctly the first time, but after asking the user if they want to enter another letter, the list of words from the file are displayed multiple times. The number of times the list prints is incrementing ex. 1,2,3...
Expected result: List of words for one letter will print once
Actual result: List of words prints more than once every time the program loops. Increments with i variable.
Error messages: None
Tried:
Modifying printWords() by using a decrement.
if (i == 2){ i--; }
- Why does the answer print out twice?
- http://www.cplusplus.com/forum/beginner/199381/
- https://codereview.stackexchange.com/questions/139841/printing-out-vectorstring-char-by-char
- Changed do-while to while
Code:
/*
Description: Android/iOS application that takes in a letter and displays
tricky-to-spell words.
*/
#include "includeDeclarations.h"
#include "usingDeclarations.h"
char userLetterInput;
char userChoiceContinue;
string userFirstName;
string line;
vector <string> trickyWordsVector;
void printWords();
int main() {
cout << "----------------<>-----------\n";
cout << "Welcome to Your TRICKY WORDS Helper!\n";
cout << "----------------<>-----------\n";
cout << "\n\nEnter your first name: ";
cin >> userFirstName;
do {
cout << "\nEnter a letter [a - z]: ";
cin >> userLetterInput;
userLetterInput = toupper(userLetterInput);
if(isalpha(userLetterInput)){
cout << "\n" << userFirstName << ",\n\nHere's your list of tricky words for the letter (" << char(toupper(userLetterInput)) << "):\n" << endl;
ifstream trickyWordsFile("trickyWordsList.txt");
if (trickyWordsFile.is_open()) {
while (getline(trickyWordsFile, line)) {
if (line.size() > 0) {
trickyWordsVector.push_back(line);
}
}
} else {
cerr << "Cannot open the file.";
}
trickyWordsFile.close();
printWords();
}
cout << "\nWould you like to enter another letter [y,n]?: "; //TODO data validation
cin >> userChoiceContinue;
} while(char(tolower(userChoiceContinue)) == 'y');
cout << "\n----------------<>-----------\n";
cout << "Thank you for using Your TRICKY WORDS Helper!\n";
cout << "----------------<>-----------\n";
return 0;
} // end main()
void printWords(){
//TODO error prints list more than once.
for (int i = 0; i < trickyWordsVector.size(); i++) {
if(trickyWordsVector[i][0] == userLetterInput){
cout << trickyWordsVector[i];
cout << "\n";
}
}
} // end printWords()
usingDeclarations.h
#define cout std::cout
#define cin std::cin
#define getline std::getline
#define endl std::endl
#define string std::string
#define ifstream std::ifstream
#define cerr std::cerr
#define vector std::vector
includeDeclarations.h
#include <iostream>
#include <fstream>
#include <locale>
#include <string>
#include <vector>
trickyWordsList.txt or trickyWordsFile
Argument
Atheist
Axle
Bellwether
Broccoli
Bureau
Caribbean
Calendar
Camaraderie
Desiccate
Desperate
Deterrence
Thanks for any advice.
Run code using https://repl.it/~