Code Explanation

Hello, I have the following working code. It creates a text file with words and count the number of occurencies of identical words. The function "countWords" count this (line 10 - 17). And this function uses string and must to count the number of occurencies of identical STRINGS. But if our input

ball field field ball

the output will

ball  occured   2 times
field occured   2 times  

not

ball field field ball   occured 1 times

Could you explain me why?
Thanks in advance.

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <fstream.h>
#include <iostream.h>
#include <map.h>
#include <string>
#include <cstdlib>
#include <conio.h>

typedef std::map<std::string, int> StrIntMap;

void countWords(std::istream& in, StrIntMap& words)
{
    std::string s;

    while (in >> s)
    {
        ++words[s];
    }
}

using namespace std;

int main ()
{
  string str;

  ofstream out("test.dat");
  if(!out) {
		cout << "Cannot open file.\n";
		return 1;
}
  cout << "Enter a words: \n";
  std::getline(cin, str);
  out << str;
  out.close();

  ifstream in("test.dat");
    if(!in) {
		cout << "Cannot find file.\n";
		return 1;
}


  StrIntMap w;
  countWords(in, w);

    for (StrIntMap::iterator p = w.begin( ); p != w.end( ); ++p)
    {   
        std::cout << setw(20) << left  << p->first  << " occurred "
                  << setw(5)  << right << p->second << " times.\n";
    }

  std::cout << "\nPress any key to close";

getch();
return 0;
}
http://www.cplusplus.com/reference/string/string/operator%3E%3E/
Notice that the istream extraction operations use whitespaces as separators; Therefore, this operation will only extract what can be considered a word from the stream. To extract entire lines of text, see the string overload of global function getline.

Elsewhere:
Extracts characters from is and stores them ..., stopping as soon as ... a whitespace character is encountered
Internally, the function accesses the input sequence by first constructing a sentry object (with noskipws set to false).
noskipws==false means same as skipws==true
skipws ... leading whitespaces are discarded before formatted input operations.



In other words:
1. You std::getline entire line into a string.
2. You write that string into a file.
3. You read one "word" at a time from the file with the >>
3. You read one "word" at a time from the file with the >>

How does it take place?
In line 14.
Topic archived. No new replies allowed.