C++/file
Expert: vijayan - 2/2/2009
Questioni have writen a class and then i have writen another class using an object of the first class! now i want to save an object of the second class on a file!
class table{
public:
vector< vector<string> >
and then the other one:
class project{
public:
vector<table> db;
now the object of class project that i wantt to save is named dataBase.
how should i do that?
i need a piece of code!
pleaze answer az soon az possible! i need it awfully early!
thank you!
Answeruse a std::ofstream to write to a file and a std::ifstream to read from a file. see:
http://www.cplusplus.com/doc/tutorial/files.html
since the primary underlying data that you need to read or write is a string, the simplest way is to use a text file and write them out one string per line of text. to read a complete line from an input stream into a C++ std::string, use std::getline.
http://www.cplusplus.com/reference/string/getline.html
writing a vector of strings to an output stream is easy:
a. write the number of strings
b. write the strings, one per line.
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
using namespace std ;
void save_vector_of_strings( vector<string>& vec, ostream& stream )
{
stream << vec.size() << '\n' ; // write out number of strings in the vector
// write the strings one string per line
for( size_t i = 0 ; i < vec.size() ; ++i )
stream << vec[i] << '\n' ;
}
and to read it back:
bool load_vector_of_strings( vector<string>& vec, istream& stream )
{
vec.clear() ; // make it an empty vector
std::size_t n = 0 ;
stream >> n >> ws ; // read number of strings in the vector, discard terminating newline
if( !stream ) return false ; // read failed
// read the strings one string per line and add them to the vector
string line ;
for( size_t i = 0 ; i < n ; ++i )
if( getline( stream, line ) ) vec.push_back( line ) ;
return true ; // success
}
a table is just a vector of vectors, so:
class table
{
public:
vector< vector<string> > data ;
void save_table( ostream& stream )
{
stream << data.size() << '\n' ; // write out number of vectors
// write the vectors
for( size_t i = 0 ; i < data.size() ; ++i )
save_vector_of_strings( data[i], stream ) ;
}
bool load_table( istream& stream )
{
std::size_t n = 0 ;
stream >> n >> ws ; // read number of vectors
if( !stream ) return false ; // read failed
// read the vectors one by one and add them to the vector
vector<string> strings ;
for( size_t i = 0 ; i < n ; ++i )
{
if( load_vector_of_strings( strings, stream ) ) data.push_back( strings ) ;
}
return true ; // success
}
// ...
};
a project is a vector of tables, so the same approch would extend to that too.