1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
|
#include <iostream>
#include <vector>
#include <string>
using namespace std;
//======================================================================
// Add to a collection of delimited items
void delimited( string text, string before, string after, vector<string> &collection )
{
int p, q = 0;
while ( true )
{
p = text.find( before, q ); if ( p == string::npos ) return;
p += before.size();
q = text.find( after, p ); if ( q == string::npos ) return;
collection.push_back( text.substr( p, q - p ) );
q += after.size();
}
}
//======================================================================
// Overload for a single delimited item (if there are several it will return the first)
string delimited( string text, string before, string after )
{
int p, q = 0;
p = text.find( before, q ); if ( p == string::npos ) return "";
p += before.size();
q = text.find( after, p ); if ( q == string::npos ) return "";
return text.substr( p, q - p );
}
//======================================================================
string trim( string s, string junk = " " )
{
int i = s.find_first_not_of( junk );
if ( i == string::npos ) return "";
int j = s.find_last_not_of( junk );
return s.substr( i, j - i + 1 );
}
//======================================================================
struct Account
{
string name;
double balance;
double rep;
};
ostream &operator << ( ostream &strm, const Account &a )
{
return strm << "Name: " << a.name << '\n' << "Balance: " << a.balance << '\n' << "Rep: " << a.rep << '\n';
}
//======================================================================
int main()
{
string bank = " [Bank]\n"
" [Account]\n"
" [Name]Lastchance[/Name]\n"
" [Balance]50[/Balance]\n"
" [Rep]23[/Rep]\n"
" [/Account]\n"
" \n"
" [Account]\n"
" [Name]Cplusplus[/Name]\n"
" [Balance]54[/Balance]\n"
" [Rep]13[/Rep]\n"
" [/Account]\n"
" [/Bank]\n";
// Get a vector of strings for whole accounts
vector<string> accountStrings;
delimited( bank, "[Account]", "[/Account]", accountStrings );
// Generate account objects - TO DO: ERROR CHECKING
vector<Account> accounts;
for ( string a : accountStrings )
{
string name = trim( delimited( a, "[Name]" , "[/Name]" ) );
double balance = stod( delimited( a, "[Balance]", "[/Balance]" ) );
double rep = stod( delimited( a, "[Rep]" , "[/Rep]" ) );
accounts.push_back( { name, balance, rep } );
}
// Output
for ( const Account &a : accounts ) cout << a << "\n";
}
| |