/ Published in: C++
Expand |
Embed | Plain Text
#include <fstream> #include <iostream> #include <string> using namespace std; int main() { int choice;//A control variable for the user's choice string FirstName, LastName; //string variables string FileName; int Age; //numeric variable //We ask the user what he wants to do cout<<"What do you want to do?n"; cout<<"(1) Write a file with your name and agen"; cout<<"(2) Read from a file your name and agen"; cin >> choice; if (choice==1){ //ask the user for some input to save cout << "Enter First Name: "; cin >> FirstName; cout << "Enter Last Name: "; cin >> LastName; cout << "Enter Age: "; cin >> Age; cout << "nEnter the name of the file you want to create: "; cin >> FileName; /* * Here is the important part: * * 1)We create a new output stream which will be used to save data into the file * In this case the 'ofstream'constructor needs the filename and the stream type * a)IMPORTANT: The filename path must be a C 'char' type and not a string, so we convert the string * using the 'cstr()' function * b)In this case we want to create an output file which will contain ASCII data hence we use * the ios::out' modifier * * 2)We use the ofstream the same way we use the 'cout' stream. With the '<<' operator we throw data in * the stream which are in turn saved into the file * a)IMPORTANT: Note that we break the line after each variable by saving 'n' * This is necessary here because if we don't, when reading the file the multiple variables will be considered * as one variable. */ ofstream Students(FileName.c_str(), ios::out); Students << FirstName << "n" << LastName << "n" << Age; } else if (choice==2){ cout << "Enter the name of the file you want to open: "; cin >> FileName; ifstream Students(FileName.c_str()); Students >> FirstName >> LastName >> Age; cout << "nFirst Name: " << FirstName; cout << "nLast Name: " << LastName; cout << "nEnter Age: " << Age; cout << "nn"; } return 0; }
You need to login to post a comment.
