c++ - 文件内容写入队列并统计元音字母的个数

标签 c++

我需要写两个函数:

  • 1个函数)需要从文件中读取单词并将单词写入队列。
  • 2个函数)你需要计算队列单词中每个记录了多少个元音。

我放弃了我能做的一切。我需要你的帮助:

  1. 我做的第一个功能对吗?(5个元素)
  2. 我做对了吗 3?
  3. 我是否正确输出到 main?

看我一会儿 筛选为什么没有推断出 (((

std::queue<std::string> queue;
std::string str;
void ProduceData()
{
    const std::string& pathToFile = "D:\\text.txt";
    unsigned number = 5;
    std::ifstream stream(pathToFile);
    if (!stream)
    {
        std::cout << "Can not open file" << "\n";
    }
    while (stream >> str)
    {
        for (size_t index = 0; index < number; ++index)
        {
            stream >> str;
            queue.push(str);
        }
    }
}

bool isVowel(const char ch)
{
    switch (ch)
    {
       case 'A':
       case 'a':
       case 'E':
       case 'e':
       case 'I':
       case 'i':
       case 'O':
       case 'o':
       case 'U':
       case 'u':
         return true;
       default:
        return false;
  }
}
void ConsumeData()
{
    while (!queue.empty())
    {
       const std::string& str = queue.front();
       std::size_t numVowels = std::count_if(str.begin(), str.end(), isVowel);
        std::cout << str << ": " << numVowels;
        queue.pop();
    }
}


int main()
{
  ConsumeData();
   return 0;
}

最佳答案

我要回答这个问题,因为我从来没有机会使用 istreambuf_iterator .要查找元音的总数,给定有效的 ifstream 输入,您可以执行以下操作:

count_if(istreambuf_iterator<char>(input), istreambuf_iterator<char>(), [](const auto i) { return i == 'A' || i == 'a' || i == 'E' || i == 'e' || i == 'I' || i == 'i' || i == 'O' || i == 'o' || i == 'U' || i == 'u'; } )

要查找和输出每个单词的元音计数,您可以使用带有 istream_iteratorcount_if :

auto count = 0;

for(auto i = istream_iterator<string>(input); i != istream_iterator<string>(); ++i) {
    cout << ++count << ": " << count_if(cbegin(*i), cend(*i), [](const auto i) { return i == 'A' || i == 'a' || i == 'E' || i == 'e' || i == 'I' || i == 'i' || i == 'O' || i == 'o' || i == 'U' || i == 'u'; } ) << endl;
}

Live Example

关于c++ - 文件内容写入队列并统计元音字母的个数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48746802/

相关文章:

c++ - 如何提高迭代精度?

c++ - 如何在给定起始位置之前查找容器中的元素?

c++ - 静态对象如何跨 DLL 和 Windows 二进制内存共享

c++ - 如何有效地实现 std::tuple 使得空类型的元组本身就是空类型?

c++ - std::transform 中的输入迭代器和输出迭代器来自同一个容器是否安全?

c++ - 自定义结构和关系重载生成错误

c++ - std::foward 的第二次重载(cppreference.com 上的示例)

c++ - 同时就地 std::sort 键 vector 和值 vector

c++ - 如何控制销毁堆对象的顺序?

c++ - 有没有一种使用 C++ 在 mac OS X 中打开一个(或多个)opengl 窗口的简单方法?