In: Computer Science
Objectives:
Background
Assume you're working on a contract where the company is building a e-mailing list. Your task is to write a C++ program that reads through an e-mail stored in the current working directory, called mail.dat, and outputs every email address found as individual lines to a file called email_list.dat. For this assignment, if a whitespace delimited string of characters has an embedded commercial at sign (@) inside it (that is, anywhere in the string), we shall consider it an e-mail address. (Yes, this is somewhat simplistic, but this is more about practice even though this allows an email to have an @ sign at the beginning/end of an address which would not be allowed in the "real world".) However, you will need to trim any trailing commas. Thus the string "[email protected]," must appear in the output file as "[email protected]" with the trailing comma removed. Only commas at the end of a string are considered trailing; do not remove non-trailing commas. Do not worry about any other punctuation characters; the only editing your program must do is to remove trailing commas.
C++ Program :
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string str;
int n;
ifstream in("mail.dat"); // opens input file
ofstream out("email_list.dat"); // writes to output file
while(in>>str) // read the strings in file until end of file
{
n = str.length(); // length of word or string
for(int i=0; i<n; i++)
{
if(str[i] == '@') // search for @ in a string in the input file
{
if(str[n-1] == ',') // if a trailing comma is found then this will ommit it
{
n=n-1; // trim the string by 1 character
}
for(int j =0; j<n; j++)
{
out<<str[j]; // print the whole string which is email-address to output file
}
out<<"\n"; // print a next line in output file
}
}
}
return 0;
}
Screenshots and Outputs :
Code :
Input file :
mail.dat
Output file :
email_list.dat