步骤1:打开文件。
使用文件流(fstream)中的open()函数打开文件并获取文件句柄。
fstream file; file.open("example.txt", ios::in);
步骤2:创建计数器。
使用变量来表示元音字母和单词的计数。
int vowelCount = 0; int wordCount = 0;
步骤3:遍历文件。
使用while循环不断读取文件中的每一个单词,直到到达文件结尾。然后,逐个检查每个单词中的字母,以判断它们是否为元音字母。
string word; while (file >> word) { wordCount++; for (char c : word) { if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { vowelCount++; } } }
步骤4:关闭文件。
在完成文件的读取和计数后,使用close()函数关闭文件。
file.close();
步骤5:输出结果。
输出元音字母和单词的计数。
cout << "Vowel count: " << vowelCount << endl; cout << "Word count: " << wordCount << endl;
完整代码示例:
#include
using namespace std;
int main() { fstream file; file.open("example.txt", ios::in);
int vowelCount = 0;
int wordCount = 0;
string word;
while (file >> word) {
wordCount++;
for (char c : word) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowelCount++;
}
}
}
file.close();
cout << "Vowel count: " << vowelCount << endl;
cout << "Word count: " << wordCount << endl;
return 0