#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 循环结束时,程序将元音计数错误。如果我不这样做,程序会在我运行时卡住。你能帮我么?谢谢。
提示:
我必须使用
字符串元音 = "aAeEiIoOuU";
如果 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/