Sign in to follow this  
MadsGustaf

help with understanding code..

Recommended Posts

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]))
  {
   ++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[i] << endl;
  }
}
    

thanks in advance!

Share this post


Link to post
Share on other sites
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".

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this