[英]The contents of the file are written to the queue and count the number of vowels
我需要編寫兩個函數:
我放棄了我能做的一切。 我需要你的幫助:
在我身上一會兒屏幕上為什么不演繹的任何內容(((
std::queue<std::string> queue;
std::string str;
void ProduceData()
{
const std::string& pathToFile = "D:\\text.txt";
unsigned number = 5;
std::ifstream stream(pathToFile);
if (!stream)
{
std::cout << "Can not open file" << "\n";
}
while (stream >> str)
{
for (size_t index = 0; index < number; ++index)
{
stream >> str;
queue.push(str);
}
}
}
bool isVowel(const char ch)
{
switch (ch)
{
case 'A':
case 'a':
case 'E':
case 'e':
case 'I':
case 'i':
case 'O':
case 'o':
case 'U':
case 'u':
return true;
default:
return false;
}
}
void ConsumeData()
{
while (!queue.empty())
{
const std::string& str = queue.front();
std::size_t numVowels = std::count_if(str.begin(), str.end(), isVowel);
std::cout << str << ": " << numVowels;
queue.pop();
}
}
int main()
{
ConsumeData();
return 0;
}
我要回答這個問題,因為我永遠沒有機會使用istreambuf_iterator
。 給定有效的ifstream input
,要查找元音的總數,您可以執行以下操作:
count_if(istreambuf_iterator<char>(input), istreambuf_iterator<char>(), [](const auto i) { return i == 'A' || i == 'a' || i == 'E' || i == 'e' || i == 'I' || i == 'i' || i == 'O' || i == 'o' || i == 'U' || i == 'u'; } )
要查找和輸出每個單詞的元音計數,可以將count_if
與istream_iterator
:
auto count = 0;
for(auto i = istream_iterator<string>(input); i != istream_iterator<string>(); ++i) {
cout << ++count << ": " << count_if(cbegin(*i), cend(*i), [](const auto i) { return i == 'A' || i == 'a' || i == 'E' || i == 'e' || i == 'I' || i == 'i' || i == 'O' || i == 'o' || i == 'U' || i == 'u'; } ) << endl;
}
我已經注釋了將isVowel
作為函數參數發送給它時用於計算元音數量的方法,尚不清楚該方法主體如何使用函數isVowel
。 而是使用下面的代碼,這對您來說更清晰。
while (!queue.empty())
{
const std::string& str = queue.front();
//std::size_t numVowels = std::count_if(str.begin(), str.end(), isVowel);
std::size_t numVowels = 0;
int i = 0;
while(i < str.length())
{
if(isVowel(str[i++]))
numVowels++
}
std::cout << str << ": " << numVowels;
queue.pop();
}
如下更改代碼,然后嘗試
while (!queue.empty())
{
const std::string& str = queue.pop();//queue.front();
//std::size_t numVowels = std::count_if(str.begin(), str.end(), isVowel);
std::size_t numVowels = 0;
int i = 0;
while(i < str.length())
{
if(isVowel(str[i++]))
numVowels++
}
std::cout << str << ": " << numVowels;
//queue.pop();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.