-2

My homework is as follows:

Step Two - Create a file called connections.txt with a format like:

Kelp-SeaUrchins
Kelp-SmallFishes

Read these names in from a file and split each string into two (org1,org2). Test your work just through printing for now. For example:

  cout <<  “pair  =  “ << org1 <<  “ , “ << org2 << endl;

I am not sure how to split the string, that is stored in a vector, using the hyphen as the token to split it. I was instructed to either create my own function, something like int ind(vector(string)orgs, string animal) { return index of animal in orgs.} or use the find function.

1 Answers1

0

Here is one approach...

Open the file:

ifstream file{ "connections.txt", ios_base::in };
if (!file) throw std::exception("failed to open file");

Read all the lines:

vector<string> lines;
for (string line; file >> line;)
    lines.push_back(line);

You can use the regex library from C++11:

regex pat{ R"(([A-Za-z0-9]+)-([A-Za-z0-9]+))" };
for (auto& line : lines) {
    smatch matches;
    if (regex_match(line, matches, pat))
        cout << "pair = " << matches[1] << ", " << matches[2] << endl;
}

You will have to come up with the pattern according to your needs.
Here it will try to match for "at least one alphanumeric" then a - then "at least one alphanumeric". matches[0] will contain the whole matched string.
matches[1] will contain first alphanumeric part, i.e. your org1
matches[2] will contain second alphanumeric part, i.e. your org2
(You can take them in variables org1 and org2 if you want.)


If org1 and org2 don't contain any white spaces, then you can use another trick.

In every line, you can replace - with a blank.(std::replace).
Then simply use stringstreams to get your tokens.


Side note: This is just to help you. You should do your homework on your own.
Sam
  • 1,842
  • 3
  • 19
  • 33