What is the easiest way code parsing string input like the following:
WORD WORD2
WORD3 WORD4
WORD5
WORD6
That is, an unknown number of pairs of words followed by a blank line followed by an unknown number of words one-per line. I want to put the first group of these words into a map, and the second list of words into a vector.
Using getline has problems discovering when the first group of paired words terminates.
A simple matter of using
getlineand some containers:If you want to make sure that the first part of the file consists precisely of pairs of words with a single region of whitespace in between, you can strengthen the condition to this:
Similarly, you can add a check that the second part of the file contains no whitespace if you like. Finally, you could use
insert()for the map to check that there are no duplicate keys; in C++11, you should be able to saym.emplace(std::move(x), std::move(y));. And anunordered_mapis probably a lot more efficient with strings.