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
|
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
vector<string> grab( istream &strm, string tag );
//======================================================================
int main()
{
stringstream strm( "{id:1234567,first:Mary,last:Green,DOB:1996-10-03,GPA:4.0}\n"
"{id:1234568,first:Peter,last:White,DOB:1997-05-22,GPA:3.8}\n"
"{id:1654238,first:Nick,last:Park,DOB:1995-08-18,GPA:4.0}\n"
"{id:1234587,first:Katy,last:Green,DOB:1995-08-18,GPA:4.0}\n" );
string tag = "first:"; // Tag, including semicolon
vector<string> names = grab( strm, tag );
for ( string s : names ) cout << s << " ";
}
//======================================================================
vector<string> grab( istream &strm, string tag )
{
vector<string> result;
string line;
while ( getline( strm, line ) ) // Read one line
{
int p = line.find( tag ); // Find the start of the tag
if ( p == string::npos ) continue; // Ill-formed string; ignore rest of line
p += tag.size(); // Get beyond the tag
int q = line.find_first_of( ",}", p ); // First thing after data
result.push_back( line.substr( p, q - p ) ); // Add to collection
}
return result;
}
//======================================================================
| |