completed Madlib comes out with truncated words. I believe the cin.Ignore() needs to go in main and
Fantastic news! We've Found the answer you've been seeking!
Question:
completed Madlib comes out with truncated words. I believe the cin.Ignore() needs to go in main and not in the loop I've moved it around everywhere to no avail.
#include #include #include #include using namespace std; string generateMadLib(vector& madLibs, vector& labels); string getArticle(string word); int main() { // Receive the name of the MadLib from the user string madLibName; cout << "Which MadLib do you want to use? (accident, shopping, or trip): "; cin >> madLibName; // Loop validity check of the files existing ifstream madLibFile(madLibName + ".txt"); ifstream labelFile(madLibName + "_labels.txt"); while (!madLibFile || !labelFile) { cout << "Error: The MadLib or its labels file could not be found." << endl; return main(); } // Read in the MadLib and label files into separate string vectors vector madLibs; vector labels; string line; string madLibComplete; while (getline(madLibFile, line)) { madLibs.push_back(line); } while (getline(labelFile, line)) { labels.push_back(line); } // Call generateMadLib to generate the MadLib madLibComplete = generateMadLib(madLibs, labels); // Display the completed story cout << "Here is your completed MadLib:" << endl; cout << madLibComplete << endl; return 0; } string generateMadLib(vector& madLibs, vector& labels) { for (int i = 0; i < madLibs.size(); i++) { string madLib = madLibs[i]; int pos = madLib.find("REPLACE"); while (pos != string::npos) { string label = labels[i]; string article = getArticle(label); cout << "Enter " << article << " " << label << ": "; string userInput; cin.ignore(1); // Clear the newline character left in the buffer **** need to place in the main**** getline(cin, userInput); madLib = madLib.replace(pos, 7, userInput); pos = madLib.find("REPLACE"); } return madLib; } } string getArticle(string word) { string vowels = "aeiou"; char firstChar = word[0]; if (vowels.find(firstChar) != string::npos) { return "an"; } else { return "a"; } }
Related Book For
Posted Date: