Upload
dennis-thompson
View
215
Download
0
Embed Size (px)
Citation preview
Quiz 2 Results
What Is Wrong?#include <iostream>#include <string.h>using namespace stdint Main(){// Say Hello 4 timesfor(i == 0; i < 3; i++){
cout >> "Hello World!" << endl;}return(0);
}
What Is Wrong? (Corrections)#include <iostream>#include <string>using namespace std;int main(){int i;for(i = 0; i < 3; i++){
cout << "Hello World!" << endl;}return(0);
}
Files• Data in Main Memory is “volatile”
• File: Place for “permanent” data storage
• C: drive, A: drive, Flash drive, etc.
Disk
File
Main Memory
progEx2Prob3.exe
main()
int num;
string firstname;
Output File Streams• In C++, the Programmer Can Declare Output Streams#include <iostream>#include <fstream>using namespace std;ofstream outputStream; //ofstream objectint num1, num2, num3;cout << “Enter 3 Numbers for datafile: “;cin >> num1 >> num2 >> num3;outputStream.open(“datafile.txt”);outputStream << num1 << “ “; outputStream << num2 << “ “; outputStream << num3;outputStream.close();
Input File Streams• In C++, the Programmer Can Declare Input
Streams#include <iostream>#include <fstream>using namespace std;ifstream inputStream; //ifstream objectint num1, num2, num3;inputStream.open(“datafile.txt”);inputStream >> num1 >> num2 >> num3;inputStream.close();
To Read or Write from a File
• Declare the File Stream Object Name
• Associate a File Name with the File Stream Object by Opening the File
• Read or Write to the File using << or >> Operators
• Close the File
#include <iostream>#include <fstream>#include <string>using namespace std;
intmain(){
ifstream input;int loops, integer, i;float decimal;string name;
input.open("mydata.txt");input >> loops;for(i= 0 ; i < loops; i++){input >> integer;input >> decimal;input >> name;cout << integer << " ";cout << decimal << " ";cout << name << endl;}return(0);
}
mydata.txt file
58 9.3 Jon6 14.335 Bill0 35.67e9 Mary-23 -4.55 Smith-3 -4e3 xyz
8 9.3 Jon6 14.335 Bill0 3.567e+010 Mary-23 -4.55 Smith-3 -4000 xyz
Output:
Functions
• Lines of code with a Name()• Name()can be executed over and over
again in the same program.