First, write a simple program that will read 5 numbers from the Console (user input). Store these values into an array of int []. Using the length of the array in a for() loop and decrementing the loop counter, write the array values in reverse order to the screen. This is step one and may be enough for partial credit. If you have difficulty with this, try seeking some assistance from your instructor before going on to step two. Next, add code to read 5 words from the Console (user input). Store these values into an array of string []. Make sure the string[] array is large enough to hold at least 6 values. Store the string constant "end_of_array" into the last element of the array. Using a do...while() loop, print out the 1st and 3rd letters of each word (two letters per line) using the substring function. This is step two and should ensure you at least a passing grade. Finally, modify the above program to read the numbers in from a text file (numbers.txt), write the values in reverse order to a second file, and read the words in from a third file, displaying the results to the Console as described above. This is your completed project. Note that you should not hard code the pathname "C:\\Projects\\Unit8\\numbers.txt" to these files. If you leave the path off, the program will look for the file in the default directory (usually the same directory as the source file). This is how you should do this as your instructor will not have the same directory structure as you do. |
#include <iostream> #include <string> #include <fstream> using namespace std; int main() { //declare variables int array[5]; int counter; string words[6]; const string endWord("end_of_array"); //get the five numbers in array cout << "Please enter five numbers: "; for (counter = 0; counter < 5; counter++) { cin >> array[counter]; } cout << endl; cout << "Your numbers are: "; for(counter = 0; counter < 5;counter++) { cout << array[counter] << " "; } cout << endl; cout << "Those numbers in reverse order are: "; for (counter = 4; counter >= 0; counter--) cout << array[counter] << " "; cout << endl; //to dump any otstanding junk from standard input char trash[256]; cin.getline(trash,256,'\n'); //read 5 words from the console cout << "Please enter five words: "; for (counter = 0; counter < 5; counter++) { cin >> words[counter]; } words[5]=endWord; counter=0; //using 0 to identify first letter, 0 is the starting position just as 2 is the position of the third letter cout << "Here is the 1st and 3rd letter of each word: " << endl; do { cout << words[counter].substr(0,1); cout << words[counter].substr(2,1); cout << endl; counter++; } while( words[counter]!=endWord); cin.get(); cin.get(); return 0; } |