简体   繁体   中英

C++ - Counting the number of vowels from a file

I'm having trouble implementing a feature that counts and displays the number of vowels from a file.

Here is the code I have so far.

#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;
}

Note the question marks in the code. Questions: How should I go about counting the vowels? Do I have to convert the text to lowercase and invoke system controls (if possible)? Also, as for printing the number of vowels in the end, which string variable should I use, (see s.?)?

Thanks

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

You can using <algorithm> 's std::count_if to achieve this :

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

Or

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

Also read Why is iostream::eof inside a loop condition considered wrong?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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