初学者(大多数情况下,无论如何)在这里。我正在开发一个程序,它从字典文件中获取单词,将其循环到一个字符串中,然后找到一个特定的子字符串,每个单词可能出现多次。这个节目正在通过" Cie"和" Cei"查看每个弹出文件的次数。我大部分时间都在工作,它确实准确地获得了#34; cei"的正确时间。但是,它会向tally
添加几个额外的增量,使其显得微不足道。这是代码:
struct Dictionary
{
void checker(ifstream&);
void out();
private:
int tally, tally2 = 0;
};
void Dictionary::checker(ifstream&usa)
{
string k;
while (usa >> k)
{
transform(k.begin(), k.end(), k.begin(), ::tolower);
string::size_type start_pos = 0;
while(string::npos != (start_pos = k.find(cie, start_pos)))
{
tally++;
++start_pos;
}
string::size_type begin_pos = 0;
while(string::npos != (begin_pos = k.find(cei, begin_pos)))
{
tally2++;
++begin_pos;
}
}
}
void Dictionary::out()
{
cout << "The number of words cie is used in is: " << tally << endl;
cout << "The number of words cei is used in is: " << tally2 << endl;
}
int main()
{
try{
//string american("/usr/share/dict/american");
ifstream american {"./american.rtf"};
if (!american)
throw runtime_error("Can't open input file.");
Dictionary words;
words.checker(american);
words.out();
}
catch(const runtime_error& e)
{
cerr << "Exception: " << e.what() << endl;
}
return 0;
}