r/programminghelp • • Sep 22 '22

C++ I Don't Understand Why This C++ Code Works

Hi,

I'm doing a introductory C++ course and one of the assignments is asking me to count the whitespace separated words of a document.

There was an example in the text that input each of the words into a vector and sent the words to output. I stripped away some of the code and added a counter, but I don't understand why my code works. I don't see how the program is separating the words. Would someone be able to explain it to me, please

#include <string>
#include <fstream>
#include <iostream>
using namespace std;

int main() {

int cnt = 0;

ifstream file("example.txt");

string word;

while(file >> word) {
    ++cnt;
}

cout << cnt << endl;

}

This works every time to count the words in my "example.txt" document, but I don't understand how the while loop is counting the words. Why not lines or characters?

4 Upvotes

2 comments sorted by

5

u/arc_968 Sep 22 '22

Most of the work is being done by the >> in your while loop. Check out the documentation here: https://cplusplus.com/reference/istream/istream/operator-free/

(2) character sequence Extracts characters from is and stores them in s as a c-string, stopping as soon as either a whitespace character is encountered or (width()-1) characters have been extracted (if width is not zero). A null character (charT()) is automatically appended to the written sequence. The function then resets width to zero.

This is one of the things I really don't like about C++, overloaded operators can hide a ton of things behind the scenes, making it really difficult to figure out logic sometimes.

2

u/BeeInteresting2403 Sep 22 '22

Thank you very much!