splitting a string in fstream

basically i just need help with an algorithm this is just a snippet of my code i need to split a entire line of data. Assuming that this line is just a bunch of words seperated by a space. i need to get each line the display each word and the amount of chars in that word on its own line. My problem is how do i separate each word. I currently look for the space in between two words. reassign that into its own string then count the chars in it . How do i do find and reassign the last last word in the string as it does not have a space (' ') , it ends with a New line char.
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

string line,temp;
int letters; // how many letters
int words // how many total words
	getline(ins, line);
	ins.ignore(100, NWLN);
	while (!ins.eof())
	{

		do
		{
			temp.assign(line, 0, line.find(' '));
			line.erase(0, temp.length());

			for (int i = 0; i < temp.length(); i++)
			{
				letters++;
			}
			words++;
			outs << temp << " " << letters << endl;
			
		} while (line.length() != NWLN);
		getline(ins, line);

Last edited on
why don't you let the stream do the work? When you write stream >> string, it does just what you seem to be looking for.

1
2
3
4
5
6
7
8
    std::string line;
    while(getline(std::cin, line)) // never do "while (!stream.eof())", by the way
    {
        std::istringstream sb(line);
        std::string word;
        while(sb >> word) 
            std::cout << word << " " << word.size() << '\n';
    }

demo: http://coliru.stacked-crooked.com/a/18b60425f38cadae
Cubbi wrote:
while(sb >> word)

What does sb stand for?
> What does sb stand for?

sb is the input string stream. std::istringstream sb(line); // line 4
Topic archived. No new replies allowed.