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

时间:2015-03-13 19:39:14

标签: c++ string file counting lowercase

我无法实现计算并显示文件中元音数量的功能。

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

#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。?)?

由于

3 个答案:

答案 0 :(得分:4)

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);

答案 1 :(得分:2)

您可以使用<algorithm>&#39; 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 ;
}

同时阅读Why is iostream::eof inside a loop condition considered wrong?

答案 2 :(得分:0)

这有用吗?

char c;
int count = 0;
while(fileIn.get(c))
{
    if ((c == 'a') || (c=='e') || .......)
    {
        count++;
    }
}