Separating a file into 2 vectors and creating a new file with the vectors

I am trying to take a file that has a lot of baby names for both boys and girls and numbering them based on popularity (these names are in 3 columns, column 1 = number, column 2 = boy name, column 3 = girl name), eg. 1 Noah Emma, what I need to do is take this file and make 2 vectors for boys and girls names and then use those vectors to write 2 separate files that each number the boys names and the other to number the girls names correctly. This is all I have at the moment. Some help would be much appreciated.

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
  #include <iostream>
#include <string>
#include <vector>
#include <fstream>

using namespace std;

int main()
{
	vector<string> boy_names;
	vector<string> girl_names;
	string boy_names;
	string girl_names;

	int line_number = 0;

	ifstream file_reader("babynames 2014.txt", ios::in);

	ofstream b_out("boys 2014", ios::out);
	ofstream g_out("girls 2014", ios::out);

	if (!file_reader)
		cout << "Unable to read babyname 2014.txt. File may not be present in the current directory.";
		return -1;

		if (b_out.is_open() && g_out.is_open())
		{
			b_out << line_number++ << boy_names;
			b_out.close();

			g_out << line_number++ << girl_names;
			g_out.close();
		}

		cin.ignore();
		cin.get();

		return 0;
}
1
2
3
	if (!file_reader)
		cout << "Unable to read babyname 2014.txt. File may not be present in the current directory.";
		return -1;

This always returns -1. Multiple statements in an if-statement need to be surrounded by curly braces.

You aren't extracting anything from file_reader.

If the format is <number> <name> <name>, then you can do something like this:

1
2
3
4
5
6
7
8
9
10
ifstream file_reader("babynames 2014.txt");

int number;
string boy_name;
string girl_name;

while (file_reader >> number >> boy_name >> girl_name) // extract an int, then string, then another string, delimited by whitespace
{
    cout << number << " " << boy_name << " " << girl_name << '\n';
}

Replace cout with some file stream if you want to direct the output to a file instead.
Last edited on
Ok that solves most of my problems but the only thing I need to use in this is vectors. I need to be able to store the names of boys in one vector and store the names of girls in another vector and then call on the vectors like you did in cout. I'm still pretty new to vectors and they just seem really confusing and I don't really understand how to use them yet.
To add a name to your vector just call boy_names.push_back(boy_name);
Topic archived. No new replies allowed.