File I/O: Writing to a text file
#include
#include
#include
using namespace std;
int main()
{
char outFile[80];
ofstream outstream;
cout << "Please enter output file name: " ;
cin >> outFile;
outstream.open(outfile, ios::out | ios::trunc);
if(!outstream)
{
cout << "Error open file " << outFile << " for writing\n";
return 1;
}
outstream<<"It is easier to resist at the beginning than at the end.\n";
outstream <<" -- Leonardo da Vinci" << endl;
outstream.close();
cout << "Content written to " << outFile <<".\n";
return 0;
}
File I/O: Reading from a text file
#include
#include
#include
using namespace std;
int main()
{
char inFile[80];
char ch;
ifstream instream;
cout << "This program reads the content of a file and ";
cout << "prints it out on the screen." << endl;
cout << "Enter input file name: " ;
cin >> inFile;
instream.open(inFile, ios::in);
if(!instream)
{
cout << "Error open file " << inFile << endl;
return 1;
}
cout << "Here is the content of " << inFile << ":\n";
while (!instream.eof())
{
instream.get(ch);
if (!instream.eof())
{
cout << ch;
}
}
instream.close();
}
A simple program demonstrating structure
#include
#include
using namespace std;
int main()
{
struct personaldata
{
char *firstname;
char *lastname;
char *birthday;
int phonenum;
};
personaldata personone;
personone.firstname = "john";
personone.lastname = "doe";
personone.birthday = "12/30/1978";
personone.phonenum = 5855555;
cout << "personone's first name is: " << personone.firstname << endl;
cout << "personone's last name is: " << personone.lastname<< endl;
cout << "personone's birthday is: " << personone.birthday<< endl;
cout <<"personone's phone number is:"<
return 0;
}
Nested structure
#include
#include
using namespace std;
int main()
{
struct name
{
char *firstname;
char *lastname;
};
struct personaldata
{
name namefield;
char *birthday;
int phonenum;
};
personaldata personone;
personone.namefield.firstname = "John";
personone.namefield.lastname = "Doe";
personone.birthday = "12/30/1978";
personone.phonenum = 5855555;
cout << "First name is: " << personone.namefield.firstname << endl;
cout << "Last name is: " << personone.namefield.lastname<< endl;
cout << "Birthday is: " << personone.birthday<< endl;
cout << "Phone number is: " << personone.phonenum<< endl;
return 0;
}
Using functions in
structure
#include
#include
using namespace std;
int main()
{
struct personaldata
{
char *firstName;
char *lastName;
char *birthday;
int phonenum;
void printdat()
{
cout << "First name is: " << firstname << endl;
cout << "Last name is: " << lastname << endl;
cout << "Birthday is: " << birthday << endl;
cout << "Phone number is: " << phonenum << endl;
}
};
personaldata personone;
personone.firstname = "john";
personone.lastname = "doe";
personone.birthday = "12/30/1978";
personone.phonenum = 5855555;
personone.printdat();
return 0;
}
No comments:
Post a Comment