Re: Splitting Strings in a map<string, string>
On Apr 15, 3:15 am, byte8b...@gmail.com wrote:
Hey guys, I'm new to cpp. Trying to split a string (on whitespace)
into a map<string, string> and return map<string, string> from within
a function. I've cobbled this together from examples on the web and
experimenting myself:
map<string, string> get_areas_groups()
{
const char* file_name = "areas_groups.txt";
// area_group should be a string that looks like this: xxx xx
// Three chars a space followed by two chars.
string area_group;
// ag is a mapping of xxx to xx
map<string, string> ag;
I would strongly recommend a typedef here:
typedef std::map< std::string, std::string >
Map ;
Map area_groups ;
ifstream fin (file_name);
while (!fin.eof())
This line is definitely wrong. What you want is
while ( std::getline( fin, area_group ) ) {
{
getline(fin, area_group);
And no getline here, of course.
string buf;
stringstream ss(area_group);
while (ss >> buf)
Why not:
std::string key ;
std::string value ;
if ( ss >> key >> value >> std::ws && ss.get() == EOF ) {
area_group[ key ] = value ;
} else {
// syntax error in the line...
}
?
More likely, you want to detect duplicate keys. In that case,
inside the if:
if ( ! area_group.insert( Map::value_type( key, value )
.second ) {
// duplicate entry ...
}
At any rate, if you want exactly two entries, a loop is not the
solution.
{
cout << buf << endl;
// Here's where I can't figure things out.
// The split works OK, but not in a way conducive
// for a map insert as buf is replaced. A vector<string>
// works great here.
ag.insert(pair<string, string>("xxx", "xx"));
}
}
fin.close();
cout << ag.size() << endl;
return ag;
}
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34