Reading different lines into different arrays

I want to read from a file and if the line starts with "a" put it in one array and if the line starts with "r" put it into a different array. I know i have to use getline but i am not sure on how to do it.
Last edited on
Hey =) I did this real quick for you, try and learn from it and create your own -

My file looks like this -

r I got a left chin
b My ear is bleeding
x Cats are evil


Here is my program:

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
42
43
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
	
// http://www.cplusplus.com/doc/tutorial/files/
	string lines[3];
	string word;
	ifstream myfile("test.txt");
	if (myfile.is_open())
	{
		int index = 0;
		while (myfile >> word)
		{
			if (word == "r")
			{
				getline(myfile, lines[index]);
				index++;
			}
			else if (word == "b")
			{
				getline(myfile, lines[index]);
				index++;
			}
			else if (word == "x")
			{
				getline(myfile, lines[index]);
				index++;
			}
		}
		myfile.close();
	}

	else { cout << "Unable to open file"; }

	for (int i = 0; i < 3; i++)
	{
		cout << lines[i] << endl;
	}
	return 0;
}


output:

I got a left chin
My ear is bleeding
Cats are evil
Last edited on
Topic archived. No new replies allowed.