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 106 107 108 109 110 111 112 113 114 115 116 117 118
|
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
// Faked input file for testing
istringstream in(
"coffee [drink] \n"
"Black coffee; Cappuccino; \n"
"Latte; \n"
" \n"
"lasagne [food] \n"
"Chicken; Beef; \n"
);
//==========================================================
class Item
{
// private members (by default)
string name;
string type;
vector<string> examples;
public: // public interface
Item( string n = "", string t = "" ) : name( n ), type ( t ) {} // constructor
string getName(){ return name; }
string getType(){ return type; }
void addExample( string eg ){ examples.push_back( eg ); }
void clear()
{
name = type = "";
examples.clear();
}
void print()
{
cout << "Name: " << name << '\n'
<< "Type: " << type << '\n'
<< "Examples: ";
for ( string s : examples ) cout << s << " ";
cout << "\n\n";
}
};
//==========================================================
string trim( const string &s, const string &junk = " " ) // strips leading/trailing blanks etc.
{
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 );
}
//==========================================================
void splitByBracket( const string &line, string &name, string &type )
{
int p = line.find( '[' ), q = line.find( ']' );
name = trim( line.substr( 0, p ) );
type = trim( line.substr( p + 1, q - p - 1 ) );
}
//==========================================================
int main()
{
// ifstream in( "input.txt" ); // uncomment (and remove the stringstream above) later
vector<Item> menu;
Item item;
for ( string line; getline( in, line ); ) // Read line by line
{
if ( line.find( '[' ) != string::npos ) // If it contains '[' start a new item
{
// Put any previous item in the menu first and reset item to empty
if ( item.getName() != "" )
{
menu.push_back( item );
item.clear();
}
// Start new item
string name, type;
splitByBracket( line, name, type );
item = Item( name, type );
}
else if ( line != "" ) // Otherwise, add to the example list
{
stringstream ss( line );
for ( string eg; getline( ss, eg, ';' ); )
{
eg = trim( eg );
if ( eg != "" ) item.addExample( eg );
}
}
}
if ( item.getName() != "" ) menu.push_back( item ); // Deal with last item
// Let's see what we've got
for ( Item &item : menu ) item.print();
}
|