-
little more help?
Write a program to generate personalized junk mail. The program takes input both from an input file and from the keyboard. The input file contains the text of a letter, except that the name of the recipient is indicated by the three characters #N#. The program asks the user for a name and then writes the letter to a second file but with the three letters #N# replaced by the name. The three-letter string #N# will occur exactly once in the letter.
Hint: Have your program read from the input file until it encounters the three characters #N#, and have it copy what it reads to the output file as it goes. When it encounters the three letter #N#, it then sends output to the screen asking for the name from the keyboard.
I have everything working but the #N#. Anyone have some hints to help?
Code:
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
void add(ifstream& in_stream, ofstream& out_stream);
char NAME[20];
int main()
{
ifstream in_stream;
ofstream out_stream;
cout << "Enter your name to win a million-zillion dollars: ";
cin >> NAME;
in_stream.open("infile.dat"); //opens in_stream
if (in_stream.fail()) // tells if in_stream fails
{
cout << "Input file opening failed.\n";
exit(1);
}
out_stream.open("outfile.dat"); //opens out_stream
if (out_stream.fail()) // tells if out_stream fails
{
cout << "Output file opening failed.\n";
exit(1);
}
add(in_stream, out_stream);
in_stream.close(); //closes in_stream
out_stream.close(); //closes out_stream
cout <<"End of editiong files.\n";
return 0;
}
void add(ifstream& in_stream, ofstream& out_stream)
{
char next;
in_stream.get(next);
while(! in_stream.eof())
{
if(next == '#')
out_stream << NAME;
else
out_stream << next;
}
}
Thanks
-
Well, right now you are just searching for the '#' and will replace it.
It is not working because in your while loop in your add function, you never change next.
Simply by adding at the end of the while loop (still in the } ) another
Code:
in_stream.get(next)
it will make your code work.
Once you have that, if you still can not figure out how to check for '#N#' instead of just '#" then jsut ask again! :)
-
ya, I changed that soon after I hit "Post". hmmm Kinda funny I'm get MargaretNMargaret but I don't think that's what I really want. lol
-
I also changed the '#' to the 'N' soo now I get #Margaret#
-
Right now you are only checking for one char, you must check for three in a row.
This will utilize the putback function (which I am betting your teacher covered), and to make your life easier I would use the peek function.
So, pseudocode
Code:
if next == #
Check the next char (I would use peek) if it is not N then just output the next char.
If it is N then get that char, check the next char (again with peek) if the next char is not # then putback the char you just got.
If it is # then get it and output the name
Else output char
Hope that is clear, I am trying to help you but not do it for you!