繁体   English   中英

C++ - 计算文件中元音的数量

[英]C++ - Counting the number of vowels from a file

我在实现计算和显示文件中元音数量的功能时遇到问题。

这是我到目前为止的代码。

#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include <cstdio>

using namespace std;

int main(void)
{int i;
 string inputFileName;
 string s;
 ifstream fileIn;
 char ch;
 cout<<"Enter name of file of characters :";
 cin>>inputFileName;
 fileIn.open(inputFileName.data());
 assert(fileIn.is_open() );
 i=0;
 while (!(fileIn.eof()))
  {
  ????????????
  }
 cout<<s;
 cout<<"The number of vowels in the string is "<<s.?()<<endl;
 return 0;
}

注意代码中的问号。 问题:我应该如何计算元音? 我是否必须将文本转换为小写并调用系统控件(如果可能)? 另外,至于最后打印元音的数量,我应该使用哪个字符串变量(参见 s.?)?

谢谢

auto isvowel = [](char c){ return c == 'A' || c == 'a' ||
                                  c == 'E' || c == 'e' ||
                                  c == 'I' || c == 'i' ||
                                  c == 'O' || c == 'o' ||
                                  c == 'U' || c == 'u'; };

std::ifstream f("file.txt");

auto numVowels = std::count_if(std::istreambuf_iterator<char>(f),
                               std::istreambuf_iterator<char>(),
                               isvowel);

您可以使用<algorithm>std::count_if来实现这一点:

std::string vowels = "AEIOUaeiou";

size_t count = std::count_if
       (
            std::istreambuf_iterator<char>(in),
            std::istreambuf_iterator<char>(),
            [=]( char x) 
            {
                return   vowels.find(x) != std::string::npos  ;
            }
        );

或者

size_t count = 0;
std::string vowels = "AEIOUaeiou";
char x ;
while ( in >> x )
{
  count += vowels.find(x) != std::string::npos ;
}

另请阅读为什么循环条件中的 iostream::eof 被认为是错误的?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM