Return to Topic Menu
|
Computer Science Main Page |
MathBits.com
|
Terms of Use
|
Resource CD
SAMPLE
PROGRAM:
// sample
program to create a file with user input
// program will create a file
containing 5 sets of entries of name and age
#include<iostream.h>
#include<assert.h>
// needed to detect file
errors
#include<fstream.h>
// necessary for file I/O
#include "apstring.cpp"
int main(void)
{
apstring name, dummy;
int age;
ofstream fout;
// declares stream variable called
fout
fout.open("name_age.dat", ios :: out);
// create file
assert(! fout.fail( ));
// to detect any access errors
for(int x = 1; x <= 5; x++)
{
cout << "Enter your name: ";
// get name from user
getline(cin, name);
// allowing for multiple word
entry
cout << "Enter your age: ";
// get age from user
cin >> age;
getline(cin, dummy);
//flush the stream
fout << name << endl;
//write name to file on its
own line
fout << age << endl;
// write age to the file
}
fout.close( );
//close the file
assert(! fout.fail( ));
// to detect any errors in
closing
return 0;
}
Beware!!
When using
getline( , ) to obtain information for the
file, be sure that the string is sent to the
file as ONE LINE OF INFORMATION.
If this does not
occur, you will not be able to read the
information from the file at a future date. Do
NOT use " " to separate such strings. |
|