Chopping up a string and ... ?

I want to read a line from a file and store the values as an object of a class and add the objects to a vector(I did not define the class in this example but assume that class and its constructors function properly).

The line would contain a name and a number. My program reads the name but I do not understand how I can extract the number(s). Each value is separated by a '/' with each line ending in a '//'.

Would creating a temporary vector and iterating through the vector suffice? I'm not quite sure how to proceed.

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

using namespace std;

string getName(string line) {
	string edit;

	for (int i = 0; i < line.length(); i++) {
		if (line[i] == '/') {
			break;
		}

		edit += line[i];
	}

	return edit;
}


int main() {
	ifstream file("names.txt");
	string line, name;
	int number;
        vector<MyClass> theStuff;

	while (getline(file, line)) {
		name = getName(line);
		while( //GetTheNumber(line, number) ???) {
                   MyClass object(number, name);
                   theStuff.push_back(object);
		}
	}

	//...the rest of the code

	file.close();

	return 0;
}


names.txt:

Bob/18//
Sue/31/2//
Dale/15/21/33/67//
Cooper/21/53//
Do you realize that getline() has a optional third parameter for the delimiter?

Have you heard about stringstreams yet?

1
2
3
4
5
6
7
	while (getline(file, line)) {
	   stringstream sin(line);
           getline(sin, name, '/');
           // For a single number.
           sin >> number;
...
Last edited on
Topic archived. No new replies allowed.