Text Parsing Error

The code below is giving me problems. What am I doing wrong and how do I fix it?

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
44
45
46
47
48
49
#include <iostream>
#include <string>
#include <vector>

	/*  Parse a string into smaller pieces broken down by a marker.
	 *  Assumes that no marker exists at the beginning or end of list.
	 *  Example parse:  split("Hello,Joe,123", ",") would result:
	 *						answer[0] = "Hello"
	 *						answer[1] = "Joe"
	 *						answer[2] = "123"
	 */
	std::vector<std::string> split(std::string &str, std::string marker) {
		
		std::vector<std::string> answer;
		int pos = 0;
		int newPos = 1;

		while (newPos != std::string::npos) {

			newPos = str.find(marker, pos);
			
			//If a marker was not found, or if we are at the end of file,
			//this is our last vector value
			if (newPos == std::string::npos) {
				answer.push_back(str.substr(pos, str.length()));
				return answer;
			}

			//If we are here, we found a marker
			answer.push_back(str.substr(pos, newPos));
			
			//Reset the starting position equal to the next position after marker
			pos = newPos + 1;

		}
		return answer;
	}


int main() {

 std::string tmp1 = "Hello,Joe,123";
 std::vector<std::string> newStr = split(tmp1, ",");

 for (int i=0; i<newStr.size(); i++)
    std::cout << newStr[i] << std::endl;

return 0;
}
Last edited on
Topic archived. No new replies allowed.