I've written a program that converts a user's input phrase into pig latin (haha), but it won't print the pig latin to a .txt file I've specified in my code. The main function as follows:
#include <iostream>
#include <string>
#include <fstream>
usingnamespace std;
string convert(string w);
string cycle(string wordToChange);
void punctuationCheck(string& w, string& punct);
int main()
{
string word, pigLatin;
string punctuation;
ofstream outFile;
outFile.open("C:\\Users\\Joel\\Documents\\Visual Studio 2010\\Projects\\C++ Exercises\\Ch08\\8-3\\Pig Latin.txt");
outFile << "PHRASE CONVERTED TO PIG LATIN:" << endl << endl;
cout << "Enter a phrase to be converted to pig latin:" << endl;
cin >> word;
//check if any text was entered
while (cin)
{
punctuation.clear();
//seperate out any punctuation from end of word
punctuationCheck(word, punctuation);
//convert word to pig latin
pigLatin = convert(word);
//print pig latin to file
outFile << pigLatin << punctuation << " ";
cout << pigLatin << punctuation << " ";
cin >> word;
}
outFile.close();
return 0;
}
The bold, underlined line doesn't seem to be executing, but the cout line just below it is writing everything just fine. I'm confused, since the outFile command DOES work (writing "PHRASE CONVERTED TO PIG LATIN:") earlier in the code. Any idea why this is happening?
(My user-defined functions are working fine, so they are omitted here to keep the post shorter)
Thanks so much in advance for your advice =)
Warik
When the output file is closed, the buffer should automatically be flushed prior to closing. In other words, if you examine the output during program execution it may appear incomplete. But after the program terminates and the file is properly closed, all the data should be there.
Ah, that makes sense, because the other issue I'm having is that the while (cin) loop never stops at the end of the input. It just keeps running infinitely, putting the program in limbo. So I've been having to terminate it before checking the .txt file...
I tried changing the "while (cin)" to "while (cin >> word)" but it hasn't had any effect. Why is this loop not terminating when there is no more string input to be read?
ah... as a quick-fix to make sure the while loop terminated at the end of the input I added a char variable "checkForEnd" and this peek & if statement at the end of the while loop:
1 2 3
checkForEnd = cin.peek();
if (checkForEnd == '\n')
break;
I imagine not the most elegant solution but a fairly concise band-aid, if you will. Thanks for helping me find out what was going on, AbstractionAnon and Chervil =)