splitting a string

I have the following code and need to be able to split the string using punctuation.

The following output should be:
int
larger
(
int
first
,
int
second
)


This code does that but if there is 2 punctuation marks that are the same next to each other, it outputs them together instead of on 2 seperate lines

I have tried loads of different ways to try and overcome this but either the output is the same or it crashes.

Can anyone please point me in the right direction?
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
#include <iostream>
#include <string>
#include <vector>

int main()
{
    using namespace std;

    string const punct = "+-*/<=!>{()};,";

    string str = "int larger(int first, int second)";
    string::size_type pos = 0;
    vector<string> vec;

    while (pos != string::npos)
    {
        string::size_type end = str.find_first_of(punct, pos);

        if (end == pos) 
		{
			end = str.find_first_not_of(punct, pos);
			vec.push_back(str.substr(pos, end - pos));
			pos = end;
		}
    }

    for (int a = 0; a < vec.size(); ++a)
    {
        cout << "vector " << a << ": " << vec.at(a) << '\n'; 
    }

    return 0;
}
The if (end == pos) doesn't make sense to me. That would only be true if the first character is something that you are looking for and it isn't in that example. The way that is setup you have to check again for pos != string::npos after the find calls. You are on the right track with the looping but you need to use the debugger and step to solve the problem. Hopefully you are using a debugger that shows you the contents of the vector conveniently.
Last edited on
I am using the command line to compile as this is what it shows in my simple c++ book i have. I haven't been doing C++ for long so really appreciate any help.

With the command line I presum there is no debugging. I got really annoyed with M$ visual studio 2008 cos i couldn't create a simple file, I had to make a project. I might have to go back to that.

I don't know where you mean where i have to check again for pos != string::npos after the find calls

I have tried different things but the program keeps crashing

The project thing isn't really that hard to deal with, you can just "Create Empty Project" and you won't have to worry about anything. And VC++'s debugger is awesome IMO.

If you want to stick to the command line, you could try gdb (if you are using gcc or g++ it should be available).
The debugger is critical in this case. This is the kind of problem that debuggers were made for. If I had the time I'd step through it myself but then you wouldn't learn anything. VS2008 has a really nice debugger so try to use that first and if you have more questions then post some followup questions.
Topic archived. No new replies allowed.