使用find()和string :: npos

时间:2016-07-15 16:56:19

标签: 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&gt;&gt; ch;”在while循环结束时,程序将元音计为错误。如果我不这样做,程序会在运行时冻结。你能帮我么?谢谢。

提示:

我必须使用

  1. string vowels =“aAeEiIoOuU”;

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

2 个答案:

答案 0 :(得分:2)

问题是你在循环之外调用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++;
    }
} 

答案 1 :(得分:0)

在这段代码中:

char ch;
...
p = vowels.find(ch);

如果没有初始化,请使用ch。你怎么知道这个程序的结果是什么。另请阅读this

相关问题