Question
using c++ write a program that reads in a text file containing a list of words, and writes two text files; one containing words with
using c++ write a program that reads in a text file containing a list of words, and writes two text files; one containing words with an even number of characters, the other containing words with an odd number of characters.
The program should begin by prompting the user for the name of the input file. Validate the filename to make sure it ends in .txt. If it does not, re-prompt the user after printing an informative message. For example:
Enter the name of the input file: words.doc Only filenames ending in '.txt' are accepted! Enter the name of the input file:
The program should attempt to open the file for reading. If there is an error (for example, if the file does not exist), then the program should output an error message and exit (by returning 1 from main()). For example:
Enter the name of the input file: no_such_file.txt Failed to open file for read: no_such_file.txt
Assuming the file opens successfully, the program should prepare the two output files. These files should be named:
-even.txt -odd.txt
where
For example, if the user enters words.txt as the input file name, the corresponding output file names will be words-even.txt and words-odd.txt.
The program should now use a while loop to read in the words, count the number of characters, and write the words to the appropriate output file, each word on a separate line.
Keep counts of how many words are read and written so that you can output a summary at the end.
As an example, suppose the input file is numbers.txt which contains:
one two three four five six seven eight nine ten
The result of a program run should look like this:
Enter the name of the input file: numbers.txt 10 words read in from numbers.txt 3 words written to numbers-even.txt 7 words written to numbers-odd.txt
The program should generate numbers-even.txt:
four five nine
and numbers-odd.txt:
one two three six seven eight ten
Hints:
1) Use a while loop to validate the filename input.
2a) Use .find() to locate the position of ".txt" in the filename.
2b) Remember, the special value string::npos is returned from .find() if there is no match.
3) The .insert() method inserts a substring into a string at a given index.
4) The .size() (or .length()) method can be used to determine the length of a string.
5) The mod (%) operator can be used to determine if a number is even or odd.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started