while 循环或其他东西中的重载运算符? C++初学者在这里

Overloaded operator in while loop or something else? C++ Beginner here

我正在关注 Bruce Eckel 的 OOP in C++ 一书。我在做第 2 章的练习。有问题的练习提出以下问题

"创建一个程序来计算a的出现次数 文件中的特定单词

有多种方法可以实现这一点,例如创建一个将文件内容读入字符串的辅助函数。我是用 while 循环和 string find 方法完成的。但是,书中建议的解决方案给出了一个我不理解的相当优雅的解决方案。完全披露:我没有参加任何 class。我这样做是为了我自己的理解:)

/**
Create a program that counts the occurrence of a particular word in a file
(use the string class’ operator ‘==’ to find the word).
**/

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {

    int counter = 0;
    string key;

    cout << "Please enter the word for search: ";
    cin >> key;

    ifstream inputFile("04.txt");
    string buf;

    while (inputFile >> buf) {

        if (key == buf)
            ++counter;
    }

    cout << "Word " << key << " occurs " << counter << " time(s)." << endl;


return 0;
}

我不明白的是while循环。

    while (inputFile >> buf) {

        if (key == buf)
            ++counter;
    }

程序首先请求用户输入查找,然后使用 fstream 打开 txt 文件,然后创建一个名为 buf 的字符串。到目前为止一切顺利,但我根本不明白 while (inputFile >> buf) 。我从文档中收集到的是,这是一个重载运算符或 this operator being inherited from istream。不过,我现在只是猜测。

有人可以解释一下 while 循环中发生了什么吗? while (inputFile >> buf) 是什么意思?这里是 C++ 初学者,请多关照。

由于 inputFile 是一个 istream,这是从文件中获取输入并将其放入 buf。此外,如果您有 genericIstream >> str,它将 return 一个布尔值,指示 genericIstream 是否为空。在这种情况下,while 循环将继续,直到读取完所有文件。

我认为安德的回答不是很有帮助,所以让我为您提供这个 this。它来自 string's operator>> 官方文档,其中指出:

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.

因此,当您尝试查看 istream operator>> 时,在您的示例代码中 string's operator>> 实际上已执行。

综上所述,运算符>>逐字读取输入流(由白色分隔space),如果从那里读取某些内容,它将return为真。