Pages

Saturday, March 12, 2011

CPP - Console Data Records

#include <iostream>
#include <cstdlib>
#include <fstream>

using namespace std;

void getHelp();
void writeData();
void readData();

typedef struct{
    string name;
    string city;
    string age;
}datas;

int main(int argc, char* argv[]){
    system("color 2f");

    datas data;
    string intro = "Welcome to console prompt: type help for info";
    cout << intro << endl;


    string command = "";
    while(command != "exit"){
        if(command == "write"){
            writeData();
        }else if(command == "help"){
            getHelp();
        }else if(command == "read"){
            readData();
        }else{
            getHelp();
        }

        cout << "Enter the command: ";
        cin >> command;
    }


    return 0;

}

void getHelp(){
    string help = "write - Enter the data\n";
    help = help + "exit - Exit from the console\n";
    help = help + "read - Read from text file\n";
    help = help + "help - Help command\n";
    cout << help << endl;
}

void writeData(){

    // reading a file
    ifstream infile("E:/lola/hello.txt");
    string fileRead = "";
    if(infile.is_open()){
        while(!infile.eof()){
            string temp;
            getline(infile, temp);
            fileRead = fileRead + temp + "\n";
        }
        infile.close();
    }else{
        cout << "Cannot Open File" << endl;
    }

    // write file
    ofstream outfile("E:/lola/hello.txt");
    datas wData;

    cout << "Enter a name: ";
    getline(cin, wData.name);
    getline(cin, wData.name);
    cout << "Enter a city: ";
    getline(cin, wData.city);
    cout << "Enter an age: ";
    getline(cin, wData.age);

    fileRead = fileRead + wData.name + "\t\t" + wData.city + "\t\t" + wData.age;
    outfile << fileRead;
    outfile.close();
}

void readData(){
    ifstream infile("E:/lola/hello.txt");
    if(infile.is_open()){
        while(!infile.eof()){
            string data;
            getline(infile, data);
            cout << data << endl;
        }
    }else{
        cout << "Cannot Open File" << endl;
    }
}

No comments:

Post a Comment