help with understanding code..

Started by
2 comments, last by ToohrVyk 17 years, 1 month ago
I understand every aspect of the code (obviusly not since theres one problem, duh) but i do not understand how it read multiple words, when i read through it, it is (to me) lotical that, hence the split function returns the "word" between i-j, and only gets called once, i do not see how it can split the sentence up in words, and print them on their own line. enough talk, heres the code:
[source lang = "cpp"] #include <iostream>
#include <string>
#include <cctype>
#include <vector>

using namespace std;

vector<string> split(const string& s)
{
 vector<string> ret;
 typedef string::size_type string_size;
 string_size i = 0;
 
 while( i != s.size())
 {
  while (i != s.size() && isspace(s))
  {
   ++i;
  }
  string_size j = i;
  
  while (j != s.size() &&  !isspace(s[j]))
  {
   ++j;
  }
  if (i!=j)
  {
  ret.push_back(s.substr(i, j-i));
  i=j;
  }
  
 }
return ret; 
}

int main()
{
  cout << "please enter a sentence: ";
  string s;
  while (getline (cin, s))
  {
   vector<string> v = split(s);
 
   for (vector<string>::size_type i = 0; i != v.size(); ++i)
  		cout << v << endl;
  }
}
    

thanks in advance!
•°*”˜˜”*°•.˜”*°•..•°*”˜.•°*”˜˜”*°•..•°*”˜˜”*°•.˜”*°•.˜”*°•. Mads .•°*”˜.•°*”˜.•°*”˜˜”*°•.˜”*°•..•°*”˜.•°*”˜.•°*”˜ ˜”*°•.˜”*°•.˜”*°•..•°*”˜I am going to live forever... or die trying!
Advertisement
The function does not return a word. It returns the ret object, which is a vector of strings. This vector is filled in a loop which, for each iteration, finds the end j of the next word starting at i, and only ends when i reaches the end of the string. Hence, it will contain all the words extracted by the loop.

For better understanding, try to run the code by hand on paper, with a simple example, such as "ABC DEF".
So basicly, in the last for loop (in the main()), the reason it is writing the word on the screen (becouse it has reached the end of the v.size) is becouse it has reached the end of the string (each string containing one word) and then it acces the next string and write that on the screen?
•°*”˜˜”*°•.˜”*°•..•°*”˜.•°*”˜˜”*°•..•°*”˜˜”*°•.˜”*°•.˜”*°•. Mads .•°*”˜.•°*”˜.•°*”˜˜”*°•.˜”*°•..•°*”˜.•°*”˜.•°*”˜ ˜”*°•.˜”*°•.˜”*°•..•°*”˜I am going to live forever... or die trying!
The for loop in the main function displays the elements inside the vector, one after another. Since the vector contains the words of the original string, the words are displayed by this operation.

Then, the while loop reads the next line from the user and repeats the process.

All the splitting is performed by the split function.

This topic is closed to new replies.

Advertisement