title: How to split a text file into words?
body: <p>I am working on a assignment where I am supposed to read a file and count the number of lines and at the same time count the words in it.
  I tried a combination of getline and strtok inside a while loop, which did not work.</p>
  
  <p>file:example.txt (the file to be read).</p>
  
  <blockquote>
    <p>Hi, hello what a pleasant surprise.<br/>
    Welcome to this place.<br/>
    May you have a pleasant stay here.<br/>
    (3 lines, and some words).<br/></p>
  </blockquote>
  
  <p>Readfile.cpp</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;fstream&gt;
  #include&lt;string&gt;
  using namespace std;
  int main()
  {
    ifstream in("example.txt");
    int count = 0;
  
    if(!in)
    {
      cout &lt;&lt; "Cannot open input file.\n";
      return 1;
    }
  
    char str[255];
    string tok;
    char * t2;
  
    while(in)
    {
      in.getline(str, 255);
      in&gt;&gt;tok;
      char *dup = strdup(tok.c_str());
      do 
      {
          t2 = strtok(dup," ");
      }while(t2 != NULL);
      cout&lt;&lt;t2&lt;&lt;endl;
      free (dup);
      count++;
    }
    in.close();
    cout&lt;&lt;count;
    return 0;
  }
  </code></pre>