Tag Archives: text file
Java || Snippet – How To Read & Write Data From A File
This page will consist of a demonstration of a simple quadratic formula program, which highlights the use of the input/output mechanisms of manipulating a text file. This program will read in data from a file (numbers), manipulate that data, and output new data into a different text file.
REQUIRED KNOWLEDGE FOR THIS SNIPPET
Try/Catch - What Is It?
The "Math" Class - sqrt and pow
The "Scanner" Class - Used for the input file
The "FileWriter" Class - Used for the output file
The "File" Class - Used to locate the input/output files
Working With Files
NOTE: The data file that is used in this example can be downloaded here.
In order to read in the data .txt file, you need to save the .txt file in the same directory (or folder) as your .java file is saved in. If you are using Eclipse, the default directory will probably be:
Documents > Workspace > [Your project name]
Alternatively, you can execute this command, which will give you the current directory in which your source file resides:
System.out.println(System.getProperty("user.dir"));
Whatever the case, in order to read in the data .txt file, your program must know where it is located on the system.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
import java.io.File; // used to locate the input/output files import java.io.FileWriter; // used for file output import java.util.Scanner; // used for file input public class ReadWriteFile { public static void main(String[] args) { // declare & initialize variables Scanner infile; FileWriter outfile; double a=0,b=0,c=0; double root1=0, root2=0; System.out.println("Welcome to My Programming Notes' Java Program.n"); // use a try/catch to check to see if the input file exists, & if not then EXIT try { // this opens the input file // YOUR INPUT FILE NAME GOES BELOW infile = new Scanner(new File("INPUT_Quadratic_programmingnotes_freeweq_com.txt")); // this opens the output file // if the file doesnt already exist, it will be created outfile = new FileWriter(new File("OUTPUT_Quadratic_programmingnotes_freeweq_com.txt")); // if the file was found, this try/catch will execute, and the loop will // attempt to get the 3 numbers from the input file and place // them inside the variables 'a,b,c' try { while(infile.hasNext()) { // this assigns the incoming data to the // variables 'a', 'b' and 'c' // NOTE: it is just like a normal scanner statement a = infile.nextInt(); b = infile.nextInt(); c = infile.nextInt(); // NOTE: if you want to read in data into an array // your declaration would be like this // ------------------------------------ // a[counter] = infile.nextInt(); // b[counter] = infile.nextInt(); // c[counter] = infile.nextInt(); // ++counter; } } catch(Exception e) { // if there was an error on input, (i.e the input file contains letters) // this block will execite, and the program will exit System.err.println("There is a formatting error in the input file!n" + "The input file should contain only 3 numbersn"); System.exit(1); } // this does the quadratic formula calculations root1 = ((-b) + Math.sqrt(Math.pow(b,2) - (4*a*c)))/(2*a); root2 = ((-b) - Math.sqrt(Math.pow(b,2) - (4*a*c)))/(2*a); // this displays the numbers to screen via stdout System.out.println("For the numbers:na = "+a+"nb = "+b+"nc = "+c); System.out.println("nroot 1 = "+root1+"nroot 2 = "+root2); // this saves the data to the output file // NOTE: its almost exactly the same as the above print statement, except // the 'write' function is dependent on the "newline" (NL) method // to generate a line break String NL = System.getProperty("line.separator"); outfile.write("For the numbers:"+NL+"a = "+a+NL+"b = "+b+NL+"c = "+c); outfile.write(NL+NL+"root 1 = "+root1+NL+"root 2 = "+root2); // close the input/output files once you are done using them infile.close(); outfile.close(); } catch(Exception e) { // if the file cannot be found, this block will execute, and the // program will exit System.err.println("Error, the input file could not be found!n" +e.getMessage()); System.exit(1); } System.out.println("nProgram Success!!n"); }// end of main }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
(Remember to include the example input file)
Welcome to My Programming Notes' Java Program.
For the numbers:
a = 2.0
b = 4.0
c = -16.0root 1 = 2.0
root 2 = -4.0Program Success!!
C++ || Snippet – How To Read & Write Data From A User Specified Text File
This page will consist of a demonstration of a simple quadratic formula program, which highlights the use of the input/output mechanisms of manipulating a text file. This program is very similar to an earlier snippet which was presented on this site, but in this example, the user has the option of choosing which file they want to manipulate. This program also demonstrates how to read in data from a file (numbers), manipulate that data, and output new data into a different text file.
REQUIRED KNOWLEDGE FOR THIS SNIPPET
Fstream
Ifstream
Ofstream
Working With Files
C_str() - Convert A String To Char Array Equivalent
Getline - String Version
Note: The data file that is used in this example can be downloaded here.
Also, in order to read in the data .txt file, you need to save the .txt file in the same directory (or folder) as your .cpp file is saved in. If you are using Visual C++, this directory will be located in
Documents > Visual Studio 2010 > Projects > [Your project name] > [Your project name]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
#include <iostream> #include <fstream> #include <string> #include <cmath> #include <cstdlib> using namespace std; int main() { // declare variables // char fileName[80]; string fileName; ifstream infile; ofstream outfile; double a=0,b=0,c=0; double root1=0, root2=0; // get the name of the file from the user cout << "Please enter the name of the file: "; getline(cin, fileName); // ^ you could also use a character array instead // of a string. Your getline declaration would look // like this: // --------------------------------------------- // cin.getline(fileName,80); // this opens the input file // NOTE: you need to convert the string to a // char array using the function "c_str()" infile.open(fileName.c_str()); // ^ if you used a char array as the file name instead // of a string, the declaration to open the file // would look like this: // --------------------------------------------- // infile.open(fileName); // check to see if the file even exists, & if not then EXIT if(infile.fail()) { cout<<"nError, the input file could not be found!n"; exit(1); } // this opens the output file // if the file doesnt already exist, it will be created outfile.open("OUTPUT_Quadratic_programmingnotes_freeweq_com.txt"); // this loop reads in data until there is no more // data contained in the file while(infile.peek() != EOF) { // this assigns the incoming data to the // variables 'a', 'b' and 'c' // NOTE: it is just like a cin >> statement infile>> a >> b>> c; // NOTE: if you want to read data into an array // your declaration would be like this // ------------------------------------ // infile>> a[counter] >> b[counter] >> c[counter]; // ++counter; } // this does the quadratic formula calculations root1 = ((-b) + sqrt(pow(b,2) - (4*a*c)))/(2*a); root2 = ((-b) - sqrt(pow(b,2) - (4*a*c)))/(2*a); // this displays the numbers to screen via cout cout <<"For the numbersna = "<<a<<"nb = "<<b<<"nc = "<<c<<endl; cout <<"nroot 1 = "<<root1<<"nroot 2 = "<<root2<<endl; // this saves the data to the output file // NOTE: its almost exactly the same as the cout statement outfile <<"For the numbersna = "<<a<<"nb = "<<b<<"nc = "<<c<<endl; outfile <<"nroot 1 = "<<root1<<"nroot 2 = "<<root2<<endl; // close the input/output files once you are done using them infile.close(); outfile.close(); // stops the program from automatically closing cout<<"nPress ENTER to continue..."; cin.get(); return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
Please enter the name of the file: INPUT_Quadratic_programmingnotes_freeweq_com.txt
For the numbers
a = 2
b = 4
c = -16root 1 = 2
root 2 = -4Press ENTER to continue...
C++ || Class & Input/Output – Display The Contents Of A User Specified Text File To The Screen
The following is another intermediate homework assignment which was presented in a C++ programming course. This program was assigned to introduce more practice using the class data structure, which is very similar to the struct data structure.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
Header Files - How To Use Them
Class - What Is It?
How To Read Data From A File
String - Getline
Array - Cin.Getline
Strcpy - Copy Contents Of An Array
#Define
This program first prompts the user to input a file name. After it obtains a file name from the user, it then attempts to display the contents of the user specified file to the output screen. If the file could not be found, an error message appears. If the file is found, the program continues as normal. After the file contents finishes being displayed, a summary indicating the total number of lines which has been read is also shown to the screen.
This program was implemented into 3 different files (two .cpp files, and one header file .h). So the code for this program will be broken up into 3 sections, the main file (.cpp), the header file (.h), and the implementation of the functions within the header file (.cpp).
Note: The data file that is used in this example can be downloaded here.
Also, in order to read in the data .txt file, you need to save the .txt file in the same directory (or folder) as your .cpp file is saved in. If you are using Visual C++, this directory will be located in
Documents > Visual Studio 2010 > Projects > [Your project name] > [Your project name]
======== FILE #1 – Main.cpp ========
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
// ============================================================================ // File: Main.cpp // ============================================================================ // This program tests the "CFileDisp" object. It prompts the user for an input // filename, then attempts to display the contents of that file to stdout. // After the file contents have been displayed, a summary line indicating the // total number of lines that have been displayed is written to stdout. // ============================================================================ #include <iostream> #include <fstream> #include "CFileDisp.h" using namespace std; // ==== main ================================================================== // // ============================================================================ int main() { CFileDisp myFile; char fname[MAX_LENGTH]; int numLines; // get the filename from the user cout << "Enter a filename: "; cin.getline(fname, MAX_LENGTH); // copy the user's filename into the file object myFile.SetFilename(fname); // have the object open the file myFile.OpenFile(); // if all is good and well... if(myFile.IsValid()==true) { numLines = myFile.DisplayFileContents(); // close the file myFile.CloseFile(); // write how many lines were displayed to stdout cout << "nt*** Total lines displayed: " << numLines << endl; } return 0; }// http://programmingnotes.org/ |
======== FILE #2 – CFileDisp.h ========
Remember, you need to name the header file the same as the #include from the Main.cpp file. This file contains the function declarations, but no implementation of those functions takes place here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
// ============================================================================ // File: CFileDisp.h // ============================================================================ // This is the header file which declares the objects which are used to open // a text file and display its contents to stdout. // ============================================================================ #ifndef CFILE_DISP_HEADER #define CFILE_DISP_HEADER #include <fstream> using namespace std; #define MAX_LENGTH 256 class CFileDisp { public: // constructor CFileDisp(); // member functions void SetFilename(char newFilename[]); /* Purpose: Copy the user's filename into the file object */ void OpenFile(); /* Purpose: Open's the file which is specified by the user */ bool IsValid(); /* Purpose: Checks if the file exists. Post: Returns false if file cannot be found */ int DisplayFileContents(); /* Purpose: Display's the file contents to stdout Post: Returns the total number of lines contained in the file */ void CloseFile(); /* Purpose: Closes the file */ // destructor ~CFileDisp(); private: bool m_bIsValid; char m_filename[MAX_LENGTH]; ifstream m_inFile; }; #endif // CFILE_DISP_HEADER // http://programmingnotes.org/ |
======== FILE #3 – CFileDisp.cpp ========
This is the function implementation file for the CFileDisp.h class. This file can be named anything you wish as long as you #include “CFileDisp.h”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
// ============================================================================ // File: CFileDisp.cpp // ============================================================================ // This file implements the functions which are declared in the CFileDisp // class, which is located in CFileDisp.h // ============================================================================ #include <iostream> #include <cstring> #include <string> #include "CFileDisp.h" using namespace std; CFileDisp::CFileDisp() { m_bIsValid = 0; }// end of CFileDisp void CFileDisp::SetFilename(char newFilename[]) { strcpy(m_filename,newFilename); }// end of SetFilename void CFileDisp::OpenFile() { m_inFile.open(m_filename); }// end of OpenFile bool CFileDisp::IsValid() { if (m_inFile.fail()) { cout << m_filename << " was not found...nn"; return false; } else { return true; } }// end of IsValid int CFileDisp::DisplayFileContents() { int total=0; string inLine; cout << endl; while(getline(m_inFile, inLine)) { cout << inLine << endl; ++total; } return total; }// end of DisplayFileContents void CFileDisp::CloseFile() { m_inFile.close(); }// end of CloseFile // this is the destructor CFileDisp::~CFileDisp() { m_bIsValid = 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Enter a filename: input_file_display_programmingnotes_freeweq_com.txt 346 130 982 90 656 117 595 415 948 126 4 558 571 87 42 360 412 721 463 47 119 441 190 985 214 509 2 571 77 81 681 651 995 93 74 310 9 995 561 92 14 288 466 664 892 8 766 34 639 151 64 98 813 67 834 369 This is a line of text! *** Total lines displayed: 10 |
C++ || Snippet – How To Read & Write Data From A File
This page will consist of a demonstration of a simple quadratic formula program, which highlights the use of the input/output mechanisms of manipulating a text file. This program will read in data from a file (numbers), manipulate that data, and output new data into a different text file.
REQUIRED KNOWLEDGE FOR THIS SNIPPET
NOTE: The data file that is used in this example can be downloaded here.
Also, in order to read in the data .txt file, you need to save the .txt file in the same directory (or folder) as your .cpp file is saved in. If you are using Visual C++, this directory will be located in
Documents > Visual Studio > Projects > [Your project name] > [Your project name]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
// ============================================================================ // Author: Kenneth Perkins // Date: Feb 12, 2012 // Taken From: http://programmingnotes.org/ // File: FileInput.cpp // Description: Demonstrates how to read data from a file // ============================================================================ #include <iostream> #include <fstream> #include <cstdlib> // used for the 'exit' command #include <cmath> using namespace std; int main () { // declare variables ifstream infile; ofstream outfile; double a=0,b=0,c=0; double root1=0, root2=0; // this opens the input file // YOUR INPUT FILE NAME GOES BELOW infile.open("INPUT_Quadratic_programmingnotes_freeweq_com.txt"); // check to see if the file even exists, & if not then EXIT if(infile.fail()) { cout<<"\nError, the input file could not be found!\n"; exit(1); // exits the program } // this opens the output file // if the file doesnt already exist, it will be created outfile.open("OUTPUT_Quadratic_programmingnotes_freeweq_com.txt"); // this loop reads in data until there is no more // data contained in the file while(infile.good()) { // this assigns the incoming data to the // variables 'a', 'b' and 'c' // NOTE: it is just like a cin >> statement infile >> a >> b >> c; // NOTE: if you want to read in data into an array // your declaration would be like this // ------------------------------------ // infile >> a[counter] >> b[counter] >> c[counter]; // ++counter; } // this does the quadratic formula calculations root1 = ((-b) + sqrt(pow(b,2) - (4*a*c)))/(2*a); root2 = ((-b) - sqrt(pow(b,2) - (4*a*c)))/(2*a); // this displays the numbers to screen via cout cout <<"For the numbers\na = "<<a<<"\nb = "<<b<<"\nc = "<<c<<endl; cout <<"\nroot 1 = "<<root1<<"\nroot 2 = "<<root2<<endl; // this saves the data to the output file // NOTE: its almost exactly the same as the cout statement outfile <<"For the numbers\na = "<<a<<"\nb = "<<b<<"\nc = "<<c<<endl; outfile <<"\nroot 1 = "<<root1<<"\nroot 2 = "<<root2<<endl; // close the input/output files once you are done using them infile.close(); outfile.close(); // stops the program from automatically closing cin.get(); return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
For the numbers
a = 2
b = 4
c = -16root 1 = 2
root 2 = -4
C++ || Input/Output – Using An Array, Sort Names From a Text File & Save The Sorted Names To A New Text File
Since we previously discussed how to sort numbers which is contained in an integer array, it is only fitting that we display a program which sorts characters that are stored in a character array.
This is an interactive program which first displays a menu to the user, allowing them to choose from 6 different modes of operation. The 6 options are described as followed:
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit
From the available choices, the user has the option of reading in names from a file, manually entering in names themselves, displaying the current names in the array, sorting the current names in the array, clearing the current names in the array, and finally quitting the program. When the user chooses to quit the program, whatever data which is currently stored within the array will automatically be saved to the output text file.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
Fstream
Ifstream
Ofstream
Character Arrays
2D Arrays
Working With Files
Pass By Reference
While Loops
For Loops
Bubble Sort
Functions
Switch Statements
Boolean Expressions
Toupper
Strcpy
Strcmp
The data file that is used in this example can be downloaded here.
Note: In order to read in the data .txt file, you need to save the .txt file in the same directory (or folder) as your .cpp file is saved in. If you are using Visual C++, this directory will be located in
Documents > Visual Studio 2010 > Projects > [Your project name] > [Your project name]
NOTE: On some compilers, you may have to add #include < cstdlib> and #include < cstring> in order for the code to compile.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 |
#include <iostream> #include <fstream> #include <iomanip> using namespace std; // const variable indicating how many names the array can hold const int TOTALNAMES = 100; // function prototypes void DisplayMenu(); int ReadInData(char names[][50], ifstream &infile); void GetUserData(char names[][50], int numberOfNames); void ClearArray(char names[][50], int numberOfNames); void SortArray(char names[][50], int numNames); void DisplayArray(char names[][50], int numNames); void SaveArrayToFile(char names[][50], int numberOfNames, ofstream &outfile); int main() { // declare variables ifstream infile; ofstream outfile; char names[TOTALNAMES][50]; char userResponse = 'Q'; int numberOfNames = 0; // display menu to user DisplayMenu(); cin >> userResponse; // keep looping thru the menu until the user // selects Q (Quit) while(toupper(userResponse)!='Q') { // switch statement indicating the available choices // the user has to make switch(toupper(userResponse)) { case 'R': numberOfNames = ReadInData(names, infile); break; case 'E': cout << "nPlease enter the number of names you want to sort: "; cin >> numberOfNames; GetUserData(names,numberOfNames); break; case 'D': DisplayArray(names, numberOfNames); break; case 'C': ClearArray(names,numberOfNames); numberOfNames=0; break; case 'S': SortArray(names, numberOfNames); break; case 'Q': break; default: cout << "nThe selected option is not apart of the list!nPlease try again.."; break; } // creates a line seperator after each task is executed cout<<endl; cout.fill('-'); cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl; // re-display's the menu to the user DisplayMenu(); cin >> userResponse; } // after the user is finished manipulating the // data, save the names to the output file SaveArrayToFile(names, numberOfNames, outfile); return 0; }// end of main // ============================================================================ // displays options to user void DisplayMenu() { cout<<" Welcome to the name sorting program..."; cout<<"nFrom the following menu, select an option"; cout<<"nR - Read in names from a file for sorting"; cout<<"nE - Enter in names manually for sorting"; cout<<"nD - Display the current names in the array"; cout<<"nS - Sort the current names in the array"; cout<<"nC - Clear the current names in the array"; cout<<"nQ - Quitn"; cout<<"n>> "; }// end of DisplayMenu // ============================================================================ // reads in data from a file int ReadInData(char names[][50], ifstream &infile) { int numberOfNames=0; // open input file infile.open("INPUT_UNSORTED_NAMES_programmingnotes_freeweq_com.txt"); if(infile.fail()) { cout<<"Input file could not be found!n" <<"Please place the input file in the correct directory.."; return 0; } else { cout << "nReading in data from the file..."; while(infile.good()) { infile >> names[numberOfNames]; ++numberOfNames; } cout << "nSuccess!"; } infile.close(); // close the infile once we are done using it return numberOfNames; }// end of ReadInData // ============================================================================ // gets data from user (names) for direct input void GetUserData(char names[][50], int numberOfNames) { cout << "nPlease enter "<<numberOfNames<<" names" << endl; for(int index=0; index < numberOfNames; ++index) { cout<<"nName #"<<index+1<<": "; cin >> names[index]; } }// end of GetUserData // ============================================================================ // clears the data contained in the array void ClearArray(char names[][50], int numNames) { if(numNames==0) { cout<<"nThe array is currently empty!n"; } else { cout<<"nDeleting the data contained in the array..."; for(int index=0; index < numNames; ++index) { strcpy(names[index],""); } cout << "nClearing Complete!"; } }// end of ClearArray // ============================================================================ // sorts the array via 'bubble sort' void SortArray(char names[][50],int numNames) { bool sorted = false; char temp[50]; if(numNames==0) { cout<<"nThe array is currently empty!n"; } else { cout << "nSorting the names contained in the array..."; // this is the 'bubble sort' and will execute only // if there is more than 1 name contained within the array // If there is only one name contained in the array, // there is no need to sort anything while((sorted == false) && (numNames > 1)) { sorted = true; for (int index=0; index < numNames-1; ++index) { if (strcmp(names[index], names[index+1]) > 0) { strcpy(temp,names[index]); strcpy(names[index], names[index+1]); strcpy(names[index+1], temp); sorted = false; } } } cout << "nSuccess!"; } }// end of SortArray // ============================================================================ // saves the current data which is in the arrya to the output file void SaveArrayToFile(char names[][50], int numberOfNames, ofstream &outfile) { // open output file outfile.open("OUTPUT_SORTED_NAMES_programmingnotes_freeweq_com.txt"); if(outfile.fail()) { cout<<"Error creating output file!"; return; } else { if(numberOfNames==0) { cout<<"nThe array contained no names.nThere was no data to save to the output file...n"; outfile<<"The array contained no names.nThere was no data to save to the output file...n"; } else { cout<<"nSaving the current contents of the array to the ouptut file.."; outfile<<"Sorted items which were contained within the array..n"; for(int index=0; index < numberOfNames; ++index) { outfile <<"Name #"<<index+1<<": " << names[index]<<endl; } cout << "nSuccess!n"; } } outfile.close(); }// end of SaveArrayToFile // ============================================================================ // displays the current contents of the array to the user // via cout void DisplayArray(char names[][50], int numNames) { if(numNames==0) { cout<<"nThe array is currently empty!n"; } else { cout << "nThe values in the array are:n"; for (int index=0; index < numNames; ++index) { cout << names[index] << endl; } cout<<"nThere is currently "<<numNames<<" names in the array!n"; } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
(Remember to include the input file)
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> d
The array is currently empty!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> q
The array contained no names.
There was no data to save to the output file...------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> e
Please enter the number of names you want to sort: 3
Please enter 3 names
Name #1: My
Name #2: Programming
Name #3: Notes------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> d
The values in the array are:
My
Programming
NotesThere is currently 3 names in the array!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> s
Sorting the names contained in the array...
Success!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> d
The values in the array are:
My
Notes
ProgrammingThere is currently 3 names in the array!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> c
Deleting the data contained in the array...
Clearing Complete!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> r
Reading in data from the file...
Success!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> d
The values in the array are:
My
Programming
Notes
C++
Java
Assembly
Lemon
Dark
Light
Black
High
Low
Cellphone
Cat
Dog
Penguin
Japan
Peace
Love
Color
White
One
Brain
Eggplant
Phalanx
Countenance
Crayons
Ben
Dover
Eileen
Bob
Downe
Justin
Elizebeth
Rick
Rolled
Sam
Widge
Liza
Destruction
Grove
Aardvark
Primal
Sushi
Victoria
Ostrich
Zebra
Scrumptious
Carbohydrate
Sulk
Ecstatic
Acrobat
Pneumonoultramicroscopicsilicovolcanoconiosis
English
Kenneth
Jessica
Pills
Pencil
Dragon
Mint
Chocolate
Temperature
Cheese
Rondo
Silicon
Scabbiest
Palpitate
Invariable
Henpecked
Titmouse
Canoodle
Boobies
Pressure
Density
Cards
Twiat
Tony
Pink
Green
Yellow
Duck
Dodge
Movie
Zoo
Xiomara
Eggs
Marshmallows
Umbrella
Apple
Panda
Brush
Handle
Door
Knob
Mask
Knife
Speaker
Wood
Orient
LoveThere is currently 100 names in the array!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> s
Sorting the names contained in the array...
Success!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> d
The values in the array are:
Aardvark
Acrobat
Apple
Assembly
Ben
Black
Bob
Boobies
Brain
Brush
C++
Canoodle
Carbohydrate
Cards
Cat
Cellphone
Cheese
Chocolate
Color
Countenance
Crayons
Dark
Density
Destruction
Dodge
Dog
Door
Dover
Downe
Dragon
Duck
Ecstatic
Eggplant
Eggs
Eileen
Elizebeth
English
Green
Grove
Handle
Henpecked
High
Invariable
Japan
Java
Jessica
Justin
Kenneth
Knife
Knob
Lemon
Light
Liza
Love
Love
Low
Marshmallows
Mask
Mint
Movie
My
Notes
One
Orient
Ostrich
Palpitate
Panda
Peace
Pencil
Penguin
Phalanx
Pills
Pink
Pneumonoultramicroscopicsilicovolcanoconiosis
Pressure
Primal
Programming
Rick
Rolled
Rondo
Sam
Scabbiest
Scrumptious
Silicon
Speaker
Sulk
Sushi
Temperature
Titmouse
Tony
Twiat
Umbrella
Victoria
White
Widge
Wood
Xiomara
Yellow
Zebra
ZooThere is currently 100 names in the array!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> q
Saving the current contents of the array to the ouptut file..
Success!
C++ || Input/Output – Find The Average of The Numbers Contained In a Text File Using an Array/Bubble Sort
This program highlights more practice using text files and arrays. This program is very similar to one which was previously discussed on this site, but unlike that program, this implementation omits the highest/lowest values which are found within the array via a sort.
The previously discussed program works almost as well as the current implementation, but where it fails is when the data which is being entered into the program contains multiple values of the same type. For example, using the previously discussed method to obtain the average by omitting the highest/lowest entries found within an array, if the array contained the numbers:
1, 2, 3, 3, 3, 2, 2, 1
The previous implementation would mark 1 as being the lowest number (which is correct) and it would mark 3 as being the highest number (which is also correct). The area where it fails is when it omits the highest and lowest scores found within the array. The program will skip over ALL of the numbers contained within the array which equal to 1 and 3, thus resulting in the program obtaining the wrong answer.
To illustrate, before the previous program computes its adjusted average scores, it will not only omit just 1 and 3 from the array, but it will also omit all of the 1’s and 3’s from the list, resulting in our array looking like this:
2, 2, 2
When you are finding the average of a list of numbers by omitting the highest/lowest scores, you don’t want to omit ALL of the values which may equal said numbers, but merely just the highest (last element in the array) and lowest (first element in the array) scores.
So if the previous implementation has subtle issues, why is it on this site? The previous program illustrates very well the process of finding the highest/lowest integers found within an array. It also works flawlessly for data in which there is non repeating values found within a list (i.e 1,2,3,4,5,23,6). So if you know you are reading in from a file in which there are non repeating values, the previous implementation works well. Often times though, developers do not know what type of data the incoming files will contain, so this current implementation is a better way to go, especially if it is not known exactly how many numbers are contained within a file.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
Fstream
Ifstream
Ofstream
Working With Files
While Loops
For Loops
Bubble Sort
Basic Math - Finding The Average
The data file that is used in this example can be downloaded here.
Note: In order to read in the data .txt file, you need to save the .txt file in the same directory (or folder) as your .cpp file is saved in. If you are using Visual C++, this directory will be located in
Documents > Visual Studio 2010 > Projects > [Your project name] > [Your project name]
NOTE: On some compilers, you may have to add #include < cstdlib> in order for the code to compile.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 |
#include <iostream> #include <fstream> using namespace std; // function prototype float FindOmittedAverage(int numbers[], int counter); int main() { // declare variables ifstream infile; ofstream outfile; float average=0; float sum =0; int highestNumber = -999999; int lowestNumber = 99999999; int numbers[100]; // open the input file in which you will read data from infile.open("INPUT_Numbers_ programmingnotes_freeweq_com.txt"); if(infile.fail()) { cout<<"nInput file not found!n"; exit(1); // there was an error, program exits } // open the output file in which the compiled data will be saved to outfile.open("OUTPUT_Averages_ programmingnotes_freeweq_com.txt"); if(outfile.fail()) { cout <<"There was an error creating the output file, press enter to terminate program."; exit(1); // there was an error, program exits } // display data to screen via cout cout <<"The numbers countained in the input file are: "; // saves data to the outfile. Notice the declaration to // save data to the outfile is the same as the ^ above cout // statment outfile <<"The numbers countained in the input file are: "; // incoming data from the file will be stored in an int array // so this counter will increment the array index every time the // program finds a new value inside the file to store inside the array int counter =0; // this while loop will read in data from the file until it reaches the end of the file // (i.e until there are no more number found within the file) // this process also stored the numbers inside the "numbers" array while(infile >> numbers[counter]) { // 'sum' variable adds the incoming numbers together // computing the sum sum += numbers[counter]; // finds the highest number contained within the incoming file if( numbers[counter] > highestNumber) { highestNumber = numbers[counter]; } // finds the lowest number contained within the incoming file if (numbers[counter] < lowestNumber) { lowestNumber = numbers[counter]; } // displays the currently found number from the file to stdout cout << numbers[counter] << ", "; // saves the currently found number from the file to the output file outfile << numbers[counter]<< ", "; ++counter; } // always close your file after your done using them infile.close(); // display the highest found number to stdout cout<< "nnThe highest and lowest numbers contained in the file are: nHighest: " << highestNumber<<"nLowest: "<<lowestNumber<<endl; // saves the highest found number to the output file outfile<< "nnThe highest and lowest numbers contained in the file are: nHighest: " << highestNumber<<"nLowest: "<<lowestNumber<<endl; // using the sum found from the above while loop, we compute the average average = sum/(counter); // display/save the average of the numbers which were contained in the // file to stdout and the output file cout<<"nThe average of the "<<counter<<" numbers contained in the file is: "<<average<<endl; outfile<<"nThe average of the "<<counter<<" numbers contained in the file is: "<<average<<endl; // function declaration which finds the omitted average of the found numbers // from the file average = FindOmittedAverage(numbers,counter); // display/save the omitted average of the numbers which were contained in the // file to stdout and the output file cout<<"nThe average of the "<<counter<<" numbers contained in the file omitting the highest and lowest scores is: "<<average<<endl; outfile<<"nThe average of the "<<counter<<" numbers contained in the file omitting the highest and lowest scores is: "<<average<<endl; // closes the outfile once we are done using it outfile.close(); return 0; } // function takes in the 'numbers' array, and 'counter' variable from // the main function as parameters, and computes the average, omitting // the highest and lowest numbers found within the array float FindOmittedAverage(int numbers[], int counter) { float sum = 0; float avg = 0; // this is a 'bubble sort' which will sort the numbers // contained within the array, from lowest to the highest // i.e (1,2,3,4,5,6,7,8) for(int iteration = 1; iteration < counter; iteration++) { for(int index = 0; index < counter - iteration; index++) { // if the previous value in the array is bigger than the next, then swap them if(numbers[index]> numbers[index+1]) { int temp = numbers[index]; numbers[index] = numbers[index+1]; numbers[index+1]= temp; } } }// end of sort // after the sorting is complete, set the highest // and lowest elements in the array to zero numbers[0]=0; numbers[counter-1]=0; // find the sum of the newly sorted array // with the highest and lowest entries being deleted (set to zero) for(int i = 0; i < counter; i++) { sum += numbers[i]; } // compute the average avg = sum / (counter-2); // return the average back to main return avg; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
(Remember to include the input file)
The numbers countained in the input file are: 12, 45, 23, 46, 11, -5, 23, 33, 50, 17, 13, 25, 15, 50,
The highest and lowest numbers contained in the file are:
Highest: 50
Lowest: -5The average of the 14 numbers contained in the file is: 25.5714
The average of the 14 numbers contained in the file omitting the highest and lowest scores is: 26.0833
C++ || Input/Output Text File Manipulation – Find Highest, Lowest, Average & Total Sum
This is a program which will utilize fstream, specifically ifstream and ofstream, to read in data from one .txt file, and it will then output selected data into an entirely new separate .txt file.
The input data file has 8 different rows, with each row containing 7 numbers on each line. The program will take in each line one at a time, manipulating the 7 numbers to receive the desired output. This program will find the highest/lowest number in each selected line, along with the total sum of all the numbers contained in that line, and the average of all the numbers. So at the end of the program, There will be 8 different sets of data compiled for each row, with the output file looking like this:
SAMPLE RUN:
- Input File -
3 5 7 3 4 5 6- Output File -
The dataset for input line #1 is: 3 5 7 3 4 5 6
The highest number is: 7
The lowest number is: 3
The total of the numbers is: 33
The average of the numbers is: 4.71
The data file that is used in this example can be downloaded here
Note: In order to read in the data .txt file, you need to save the .txt file in the same directory (or folder) as your .cpp file is saved in. If you are using Visual C++, this directory will be located in
Documents > Visual Studio > Projects > [Your project name] > [Your project name]
NOTE: On some compilers, you may have to add #include < cstdlib> in order for the code to compile.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
// ============================================================================ // Author: Kenneth Perkins // Date: Jan 6, 2012 // Taken From: http://programmingnotes.org/ // File: fileInput.cpp // Description: Demonstrates how to read and write data to a file // ============================================================================ #include <iostream> #include <fstream> using namespace std; int main () { // declare variables ifstream infile; ofstream outfile; int inputNumber = 0; int highestNum = -999999; int lowestNum = 999999; double sum = 0; double average = 0; int currentLineNum = 1; // This opens the input file infile.open("INPUT_programmingnotes_freeweq_com.txt"); if(infile.fail()) //there was an error on open, file not found { cout << "Cannot find input file, press enter to terminate program." << endl; exit (1); // there was an error, program exits } // This opens the output file outfile.open("OUTPUT_programmingnotes_freeweq_com.txt", ios::app); if(outfile.fail()) { cout <<"There was an error opening the output file, press enter to terminate program."; exit(1); // there was an error, program exits } do { cout << "The dataset for input line #" << currentLineNum << " is: "; outfile << "The dataset for input line #" << currentLineNum << " is: "; // loops thru file until we get to the last number // from the selected line // (theres 7 numbers total in each line, see input file for clarification) for(int counter = 1; counter <= 7; counter++) { infile >> inputNumber; sum += inputNumber; // calculates the total sum of #'s for each line // checks to see which number is highest/lowest from // each selected line if(inputNumber > highestNum) { highestNum = inputNumber; } if(inputNumber < lowestNum) { lowestNum = inputNumber; } // displays current number to output screen // and saves to file cout << inputNumber << "\t"; outfile << inputNumber << "\t"; }// end for loop average = sum / 7; // finds the total avg for each line // this displays data to the output screen cout << endl; cout << "The highest number is: " << highestNum << endl; cout << "The lowest number is: " << lowestNum << endl; cout << "The total of the numbers is: " << sum << endl; cout << "The average of the numbers is: " << average << endl; // outfile section here, saves data to file outfile << endl; outfile << "The highest number is: " << highestNum << endl; outfile << "The lowest number is: " << lowestNum << endl; outfile << "The total of the numbers is: " << sum << endl; outfile << "The average of the numbers is: " << average << endl << endl; // outfile section end // resets variables back to default values highestNum = -999999; lowestNum = 999999; sum = 0; average = 0; currentLineNum++; // places data on new line cout << endl << endl; } while(!infile.eof()); // loop stops once it reaches the end of file cout << endl << endl <<"\tWe have reached the end of the file!"<< endl; outfile << endl << endl <<"\tWe have reached the end of the file!"<< endl << endl; outfile.close(); // closes outfile infile.close(); // closes infile return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
LOOPS
This program utilizes one do/while loop on lines 39-97 which loops thru the input file until it reaches the end of the file. This program also uses a for loop, which is noted on line 46.
CALCULATING THE SUM
Line 50 contains the assignment operator “+=“, which will calculate a running total for all the values of each selected line.
READING IN DATA FROM FILE
This is noted in line 48, and works just like a cin statement.
OPENING FILES
File declarations, and the opening of files are highlighted on lines: 14-15, 24-25, 32-33. On line 32, the term “ios::app” means the file will append new data to the text file, instead of overwriting the old data contained within that file.
OUTPUT DATA TO FILE
This is highlighted on lines 80-84, and as you can see, the output statements are exactly the same as cout statements.
CLOSE FILES
Remember to close the files you open, as highlighted on lines 101 and 102.
Once compiling the above code, you should receive this as your output (for the 8 selected lines contained within the input text file)
The dataset for input line #1 is: 346 130 982 90 656 117 595
The highest number is: 982
The lowest number is: 90
The total of the numbers is: 2916
The average of the numbers is: 416.571The dataset for input line #2 is: 415 948 126 4 558 571 87
The highest number is: 948
The lowest number is: 4
The total of the numbers is: 2709
The average of the numbers is: 387The dataset for input line #3 is: 42 360 412 721 463 47 119
The highest number is: 721
The lowest number is: 42
The total of the numbers is: 2164
The average of the numbers is: 309.143The dataset for input line #4 is: 441 190 985 214 509 2 571
The highest number is: 985
The lowest number is: 2
The total of the numbers is: 2912
The average of the numbers is: 416The dataset for input line #5 is: 77 81 681 651 995 93 74
The highest number is: 995
The lowest number is: 74
The total of the numbers is: 2652
The average of the numbers is: 378.857The dataset for input line #6 is: 310 9 995 561 92 14 288
The highest number is: 995
The lowest number is: 9
The total of the numbers is: 2269
The average of the numbers is: 324.143The dataset for input line #7 is: 466 664 892 8 766 34 639
The highest number is: 892
The lowest number is: 8
The total of the numbers is: 3469
The average of the numbers is: 495.571The dataset for input line #8 is: 151 64 98 813 67 834 369
The highest number is: 834
The lowest number is: 64
The total of the numbers is: 2396
The average of the numbers is: 342.286We have reached the end of the file!