c++ - 用 find() 和 string::npos 计算元音

标签 c++

#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;


int main(int argc, char* argv[])
{
ifstream inf(argv[1]);
if (!inf)
 {
    cerr << "Error opening " << argv[1] <<  endl;
    return 1;
 }

char ch;
size_t count = 0;

string vowels = "aAeEiIoOuU";
size_t p;
p = vowels.find(ch);

inf >> ch;
while(!inf.eof())
{


    if (p != string::npos)
    {
        count++;
    }
 inf >> ch;      
}     


inf.close();
cout << "File " << argv[1] << " includes " << count << " vowels." << endl;
return 0;
}

我有问题

 inf >> ch;
while(!inf.eof())
{
  if ( p != string::npos)
  {
    count++
  }
       inf >> ch;
}

基本上,程序会查找 text.txt 文件并计算它有多少个元音字母。 我想在 while 循环中重复。如果我包括“inf >> ch;”在 while 循环结束时,程序将元音计数错误。如果我不这样做,程序会在我运行时卡住。你能帮我么?谢谢。

提示:

我必须使用

  1. 字符串元音 = "aAeEiIoOuU";

  2. 如果 ch 是元音字母,函数调用 vowels.find(ch) 将返回一个不是 string::npos 的索引。

最佳答案

问题是你在循环外调用了find,所以可能的解决方法是:

string vowels = "aAeEiIoOuU";
// p delcaration and call to find is removed from here
inf >> ch;
while(!inf.eof())
{
    size_t p = vowels.find(ch);
    if (p != string::npos)
    {
        count++;
    }
    inf >> ch;      
} 

但为了避免代码重复,这样更好更简洁:

while( inf >> ch )
{
    size_t p = vowels.find(ch);
    if (p != string::npos)
    {
        count++;
    }
} 

关于c++ - 用 find() 和 string::npos 计算元音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38401480/

相关文章:

c++ - C++中将一个区间分成n等份

c++ - OpenCV:如何可视化深度图像

c++ - 如何在 Clang 的标准库中提取 header 的搜索路径?

c++ - 在现代 C++11/C++14/C++17 和 future 的 C++20 中枚举到字符串

c++ - 使用 std::function 和 bind 来分配具有不同参数列表的函数

c++ - 在带有bool输入的std::function中使用boost变量

c++ - 制作复制构造函数

c++ - boost function_input_iterator range 的快捷语法

c++ - 如何使用QComboBox来选择如何保存QImage的格式

c++ - 为什么编译器允许字符串文字不是 const?