我正在阅读Bruce Eckel编写的C ++中的OOP。我正在第二章练习。有问题的练习请问以下
“创建一个程序来计算文件中的特定单词”
有多种方法可以实现此目的,例如创建一个将文件内容读入字符串的辅助函数。我用while循环和string find方法做到了。但是,本书中建议的解决方案提供了一个我不理解的相当优雅的解决方案。全面披露:我没有参加任何课程。我这样做是出于我自己的理解:)
/**
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的字符串。到目前为止,一切都很好,但是我完全不了解(inputFile >> buf)。我从文档中收集到的是这是一个重载运算符或this operator being inherited from istream。但是,我现在只是猜测。
有人可以解释一下while循环中发生了什么吗? while(inputFile >> buf)是什么意思? C ++初学者在这里,所以请客气。
由于inputFile是istream,因此将从文件中获取输入并将其放入buf中。同样,如果您有genericIstream >> str
,它将返回一个布尔值,指示genericIstream是否为空。在这种情况下,while循环将继续直到读取完所有文件。
[我认为Ender的回答没有太大帮助,因此让我为您提供this。它来自string's operator>>
官方文档,并指出:
[注意,istream提取操作将空格用作分隔符因此,此操作只会提取可以被认为是流中的一个单词。
因此,当您尝试查看istream operator>>
时,在示例代码中实际上已执行了string's operator>>
。