Question

C++ There are to be two console inputs to the program, as explained below. For each input, there is to be a default val...

C++

  1. There are to be two console inputs to the program, as explained below. For each input, there is to be a default value, so that the user can simply press ENTER to accept any default. (That means that string will be the best choice of data type for the console input for each option.)
  2. The two console inputs are the names of the input and output files. The default filenames are to be fileContainingEmails.txt for the input file, and copyPasteMyEmails.txt for the output file. The default location for these files is the working folder of the program (so do not specify a drive or folder for the default filenames). The actual names and locations of the files can be any valid filename for the operating system being used, and any existing drive and folder.
  3. It is okay for the user to select input and output names by the same name. If the user enters another name for the input file besides the default, then the default for the output file should change to be the same as that of the input file. So if the input and output filenames are the same, then the input file becomes replaced by the output file when the program is run.
  4. The output file should be overwritten, and not appended to. No warning is necessary when overwriting an already-existing file.
  5. Print each email to the output file, separated by a semicolon and a space. Include nothing before the first email message, and nothing after the last. Include nothing in the file besides email addresses and semicolon+space separators.
  6. Do not allow duplicate email addresses to appear in the output file. Since you are supposed to preserve the case of email addresses, it is possible for an email address to appear more than once, cased differently -- like [email protected] and [email protected]. In this case, store one of them in its originally-cased form -- it does not matter which one you choose as long as it is one of them and not some other casing. (So you will have to store each email in a list as you process the input file, checking to see if it is already in the list before adding it. Then use the list to write the output file after the input file has been fully processed and closed).
  7. Count the number of non-duplicate email addresses found in the input file, and list each on a separate line of console output. At the end of the list of email addresses on the console, print the total number of non-duplicate email addresses found. If the number of email addresses found is zero, do not write the output file. (That means, do not even open it.)
  8. In case an email address is split between two or more lines in the input file, ignore it. Valid email addresses must appear fully within one line of the input file. Also, each line of the input file may contain more than one email address.
  9. Include friendly, helpful labels on the console output. Instead of just printing the number of email addresses found, say something like "16 email addresses were found, and copied to the file output.txt". Or if none were found, say something like "Sorry, no email addresses were found in the file input.txt".
  10. Include a message in the console output explaining to the user to open the output file and copy/paste its contents into the "to", "cc", or "bcc" field of any email message. But explain that it is best to use the "bcc" field so that everyone's email address does not appear in the message, to protect their privacy.

Use only techniques taught in this class. Do not use regular expressions -- they are a great way to solve this problem, but we did not cover them. Do not use char arrays for strings -- they are used in C for text strings, and we are using C++. Do not use pointers other than the ways we used them for dynamic arrays, array parameters, and links. Do not use features of the STL that we did not use in class.

0 0
Add a comment Improve this question Transcribed image text
Answer #1


//libraries
#include <algorithm> // tolower
#include <cctype>
#include <deque> // collections
#include <fstream> // file I/O operations
#include <iostream>
#include <string>
using namespace std;

//Programmer defined data types
struct Emails
{
string email; // stores emails
}; // Emails

//Special compiler dependent definitions
//NONE

//global constants/variables
//NONE

//Programmer defined functions
void intro(); // program information
string setInputFileName(); // sets input file name
string setOutputFileName(string iFileName); // sets output file name
void findEmails(string iFileName, string oFileName); // find valid emails & store to output file.
bool isValidEmailCharacter(char c); // check if character is valid.

// required for conversion to lowercase
class toLower {public: char operator()(char c) const {return tolower(c);}};

//main program
int main()
{
// Output my name and objective and program information.
intro();

// Variables
string iFileName; // input file name
string oFileName; // output file name

// Ask for input file name.
iFileName = setInputFileName(); // sets input file name

// Ask for output file name.
oFileName = setOutputFileName(iFileName); // sets output file name

// Display chosen file names.
cout << endl; // separator
cout << "Input file: " << iFileName << endl; // output user's designated input file name.
cout << "Output file: " << oFileName << endl; // output user's desginated output file name.

// output a prompt to press ENTER key to continue
cout << endl << "Press [ENTER] key to continue " << endl;
cin.ignore(1000, 10); // waits for user to hit <enter> according to page 75.

// display lines with @ symbols
findEmails(iFileName, oFileName);
} // main

void intro()
{
// Output information about this program.
cout << endl << "**********************************************" << endl;
cout << "Objective: Find valid emails in files and store them to an output file.\n";
cout << "Programmer: Duane Leem\n";
cout << "Editor(s) used: Sublime Text 2\n";
cout << "Compiler(s) used: VC++ 2013\n";
cout << "File: " << __FILE__ << endl;
cout << "Compiled: " << __DATE__ << " at " << __TIME__ << endl;
cout << "**********************************************" << endl << endl;
} // intro

string setInputFileName()
{
// Variables
string iFileName; // name of input file
string dFileName = "fileContainingEmails.txt"; // default file name
bool blankFlag = false; // checks for blank user input

// Request name of file.
cout << "Enter input filename [default: fileContainingEmails.txt]: ";
getline(cin, iFileName);

// if user didn't input anything, set it to fileContainingEmails.txt
if (iFileName.length() == 0) blankFlag = true;

// decides which file name to return to main program.
if (blankFlag == true) iFileName = dFileName;

return iFileName;
} // setInputFileName

string setOutputFileName(string iFileName)
{
// Variables
string oFileName; // name of output file
string dFileName = iFileName; // default output file name
bool blankFlag = false; // checks for blank user input

// Change default file name if original input file name was default.
if (iFileName == "fileContainingEmails.txt") dFileName = "copyPasteMyEmails.txt";

// Request name of file.
cout << "Enter output filename [default: " << dFileName << "]: ";
getline(cin, oFileName);

// if user didnt input anything, set it to x.txt
if (oFileName.length() == 0) blankFlag = true;

// decides which file name to return to main program.
if (blankFlag == true) oFileName = dFileName;

return oFileName;
} // setOutputFileName

void findEmails(string iFileName, string oFileName)
{
// Variables
ifstream fin; // used for file input operations
ofstream fout; // file out operations
string fileLine; // a line from the file
string tmpEmail; // single email object (temp)
string tmpEmails; // collection (temp)
deque<Emails> emails; // empty email list

// Open file.
fin.open(iFileName.c_str());
if (!fin.good()) "Throw I/O error";

// Traverse file and look for @ symbols.
while (fin.good())
{
    getline(fin, fileLine); // grab a line from file

    // Traverse line to look for @
    for (int i = 0; i < fileLine.length(); i++)
    {
      // Displays line if an @ symbol is found.
      if (fileLine[i] == '@')
      {
        // Variables
        int s = i; // start of email
        int e = i; // end of email
        bool hasDot = false; // checks for dot in the email.
        bool isDuplicate = false; // if it's a duplicate email found
        Emails anEmail; // object for eamil

        // Checks before the @
        do
        {
          // decrements position to first valid character
          s--;

          // break if less than 0
          if (s < 0) break;
        } while (isValidEmailCharacter(fileLine[s]));

        // increments position to first valid character.
        s++;

        // Checks after the @
        do
        {
          // increments to first valid character
          e++;

          // break when at the end of file line
          if (e == fileLine.length()) break;

          // if a dot is found, set hasDot to true.
          if (fileLine[e] == '.') hasDot = true;
        } while (isValidEmailCharacter(fileLine[e]));
      
        // Display valid email.
        if (hasDot)
        {
          // Store to object.
          anEmail.email = fileLine.substr(s, e-s);

          // Check if it's a duplicate.
          for (int count = 0; count < emails.size(); count++)
          {
            // temporary lowercase to compare
            tmpEmail = anEmail.email; // single object
            tmpEmails = emails[count].email; // collection
            transform(tmpEmail.begin(), tmpEmail.end(), tmpEmail.begin(), toLower());
            transform(tmpEmails.begin(), tmpEmails.end(), tmpEmails.begin(), toLower());

            // check for duplicate
            if (tmpEmail == tmpEmails)
            {
              isDuplicate = true;
              break; // break loop
            } // if
          } // lowercase and then checks for duplicates

          // Stores in list as long as it isn't a duplicate.
          if (!isDuplicate)
          {
            emails.push_back(anEmail); // store to collection
            cout << anEmail.email << endl;
          } // if not duplicate
        } // Valid Email
      } // if
    } // for
} // while

// Tell user there are no @'s if none were found.
if (emails.size() == 0)
{
    cout << endl << "Sorry, no email addresses were found in the file " << iFileName << endl;
}
else
{
    // store emails to output file.
    fout.open(oFileName.c_str()); // opens file
    if (!fout.good()) throw "I/O error"; // checks file
    for (int count = 0; count < emails.size(); count++)
    {
      // write email to output file.
      fout << emails[count].email;
    
      // don't write a semicolon at the last email.
      if (count != emails.size()-1) fout << "; ";
    } // traverses collection and writes to file.
    fout.close(); // closes file

    // inform user
    cout << endl << emails.size() << " email addresses were found, and copied to the file " << oFileName << endl;

    // give instructions on usage.
    cout << endl << "Usage: Open the output file " << oFileName << " and copy/paste the contents\nin the TO, CC, or BCC fields of the email you are composing. It's\nbest that you use the BCC field so that everyone's email is kept\nconfidential to protect their privacy." << endl;
} // if

// Close file.
fin.close();
} // findEmails

bool isValidEmailCharacter(char c)
{
// Variables
bool result = false;

// Determine if email character is valid.
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= 48 && c <= 57) || (c == '_') || (c == '.') || (c == '-') || (c == '+'))
{
    result = true;
} // determines if character of email is valid.

return result;
} // isValidEmailCharacter

Add a comment
Know the answer?
Add Answer to:
C++ There are to be two console inputs to the program, as explained below. For each input, there is to be a default val...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • USING RAPTOR For the following Programming Challenges, use the modular approach and pseudocode to design a suitable program to solve it. Create a program that allows the user to input a list of first...

    USING RAPTOR For the following Programming Challenges, use the modular approach and pseudocode to design a suitable program to solve it. Create a program that allows the user to input a list of first names into one array and last names into a parallel array. Input should be terminated when the user enters a sentinel character. The output should be a list of email addresses where the address is of the following from: [email protected]

  • Your mission in this programming assignment is to create a Python program that will take an...

    Your mission in this programming assignment is to create a Python program that will take an input file, determine if the contents of the file contain email addresses and/or phone numbers, create an output file with any found email addresses and phone numbers, and then create an archive with the output file as its contents.   Tasks Your program is to accomplish the following: ‐ Welcome the user to the program ‐ Prompt for and get an input filename, a .txt...

  • in java Complete Program that simulates a login procedure. The program reads a list of names,...

    in java Complete Program that simulates a login procedure. The program reads a list of names, email addresses and passwords from a file p3.txt. Store the information in parallel array lists names, emails and passwords. Your program will prompt the user for their email address. If the email is not in the system, prompt the user to try again. Provide the option to quit. If the email is found in the system, prompt the user to enter their password. After...

  • Write a complete Python program with prompts for the user for the main text file (checks...

    Write a complete Python program with prompts for the user for the main text file (checks that it exists, and if not, output an error message and stop), for any possible flags (including none), and for any other input that this program may need from the user: split has an option of naming the smaller files head_tail list the first 10 lines (default) and the last 10 lines (default) in order of the given text file flag: -# output #...

  • C++ (1) Write a program to prompt the user for an input and output file name....

    C++ (1) Write a program to prompt the user for an input and output file name. The program should check for errors in opening the files, and print the name of any file which has an error, and exit if an error occurs. For example, (user input shown in caps in first line, and in second case, trying to write to a folder which you may not have write authority in) Enter input filename: DOESNOTEXIST.T Error opening input file: DOESNOTEXIST.T...

  • This assignment tests your ability to write C programs that handle keyboard input, formatted console output,...

    This assignment tests your ability to write C programs that handle keyboard input, formatted console output, and input/output with text files. The program also requires that you use ctype functions to deal with the logic. In this program, you will input from the user two characters, which should both be letters where the second letter > the first letter. You will then input a file character-by-character and output those letters that fall between the two characters (inclusively) to an output...

  • Write a C++ console application that allows your user to capture rainfall statistics. Your program should...

    Write a C++ console application that allows your user to capture rainfall statistics. Your program should contain an array of 12 doubles for the rainfall values as well as a parallel array containing the names of the months. Using each of the month names, prompt your user for the total rainfall for that month. The program should validate user input by guarding against rainfall values that are less than zero. After all 12 entries have been made, the program should...

  • c++ The program will be recieved from the user as input name of an input file...

    c++ The program will be recieved from the user as input name of an input file and and output.file. then read in a list of name, id# and score from input file (inputFile.txt) and initilized the array of struct. find the student with the higher score and output the students info in the output file obtain the sum of all score and output the resurl in output file. prompt the user for a name to search for, when it find...

  • JAVA Write a program that prompts the user to enter a file name, then opens the...

    JAVA Write a program that prompts the user to enter a file name, then opens the file in text mode and reads it. The input files are assumed to be in CSV format. The input files contain a list of integers on each line separated by commas. The program should read each line, sort the numbers and print the comma separated list of integers on the console. Each sorted list of integers from the same line should be printed together...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT