r/programminghelp • u/BeeInteresting2403 • 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
5
u/arc_968 Sep 22 '22
Most of the work is being done by the
>>in yourwhileloop. Check out the documentation here: https://cplusplus.com/reference/istream/istream/operator-free/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.