2015-03-13 59 views
0

實施功能可以計算和顯示文件中元音的數量。C++ - 計算文件中元音的數量

這是我到目前爲止的代碼。

#include <iostream> 
#include <fstream> 
#include <string> 
#include <cassert> 
#include <cstdio> 

using namespace std; 

int main(void) 
{int i; 
string inputFileName; 
string s; 
ifstream fileIn; 
char ch; 
cout<<"Enter name of file of characters :"; 
cin>>inputFileName; 
fileIn.open(inputFileName.data()); 
assert(fileIn.is_open()); 
i=0; 
while (!(fileIn.eof())) 
    { 
    ???????????? 
    } 
cout<<s; 
cout<<"The number of vowels in the string is "<<s.?()<<endl; 
return 0; 
} 

請注意代碼中的問號。 問題:我應該如何計算元音?我是否必須將文本轉換爲小寫並調用系統控件(如果可能)? 另外,至於打印最後的元音數量,我應該使用哪個字符串變量(參見s?)?

感謝

+0

您應該從上面一行開始:'while(!(fileIn.eof()))'。如果您打算閱讀文件,並假設閱讀成功,並且內容符合您的期望,則應重新考慮該決定。如果你不打算這樣做,那麼'eof'是錯誤的條件,除非你會忽略每一個無效的輸入。 – chris 2015-03-13 19:41:01

+0

您將需要學習如何思考解決計算機問題。那麼,你如何計算元音的數量呢?你需要知道元音是什麼。這是一個庫函數嗎?閱讀庫函數列表。沒有庫函數?爲自己制定一個元音列表並將其放入您的程序中。現在你需要去你的字符串中的每個字符,並通過在你的元音列表中查找它是否是元音來測試它。如果它在列表中,則將1添加到您的元音計數中。看看如何思考它可以工作? – 2015-03-13 20:00:09

回答

4
auto isvowel = [](char c){ return c == 'A' || c == 'a' || 
            c == 'E' || c == 'e' || 
            c == 'I' || c == 'i' || 
            c == 'O' || c == 'o' || 
            c == 'U' || c == 'u'; }; 

std::ifstream f("file.txt"); 

auto numVowels = std::count_if(std::istreambuf_iterator<char>(f), 
           std::istreambuf_iterator<char>(), 
           isvowel); 
+0

我個人會爲元音使用查找數組或字符串,它更靈活,並且不像世界上有一種語言...... – dtech 2015-03-13 19:56:57

+0

@ddriver'isvowel'可以很容易地改變爲使用lookup ,或支持不同的語言等,而不影響其餘的代碼 – David 2015-03-13 20:23:49

+0

謝謝,但由於我是一個初學者,並且有點慢,所以我應該在哪裏插入它,以便與我的代碼同步?我認爲C++沒有isvowel函數? – csheroe 2015-03-13 21:10:43

2

可以使用<algorithm>std::count_if來實現這一目標:

std::string vowels = "AEIOUaeiou"; 

size_t count = std::count_if 
     (
      std::istreambuf_iterator<char>(in), 
      std::istreambuf_iterator<char>(), 
      [=](char x) 
      { 
       return vowels.find(x) != std::string::npos ; 
      } 
     ); 

或者

size_t count = 0; 
std::string vowels = "AEIOUaeiou"; 
char x ; 
while (in >> x) 
{ 
    count += vowels.find(x) != std::string::npos ; 
} 

又讀Why is iostream::eof inside a loop condition considered wrong?

0

請問這有幫助嗎?

char c; 
int count = 0; 
while(fileIn.get(c)) 
{ 
    if ((c == 'a') || (c=='e') || .......) 
    { 
     count++; 
    } 
}