#include <iostream>
using namespace std;
int main()
{
string sentence;
int countv = 0, countc = 0, countspace = 0, number, s = 1;
cout << "How many sentence would you like to check? - ";
cin >> number;
while(s <= number)
{
cout << "\nSentence " << s << ":";
cin.ignore();
getline(cin, sentence);
for(int i = 0; i < sentence.length(); i++)
{
if(sentence[i] == 'a' || sentence[i] == 'e' || sentence[i] == 'i' || sentence[i] == 'o' || sentence[i] == 'u')
countv++;
else if(isspace(sentence[i]))
countspace++;
else
countc++;
}
cout << "\nSentence " << s << " result:";
cout << "\nThere are " << countv << " vowels in the sentence.";
cout << "\nThere are " << countc << " consonants in the sentence.";
cout << "\nThere are " << countspace << " whitespace in the sentence.";
countc = 0, countv = 0, countspace = 0;
s++;
cout << "\n";
}
}
我试图计算多个字符串中元音和辅音的数量,但是由于某种原因,它只给出了第一个字符串的正确输出。
我注意到,对于接下来的字符串(第二个,第三个等等),它不计算字符串的第一个字母,这是为什么?
1条答案
按热度按时间t8e9dugd1#
代码 * 忽略 * 每个字符串后面的第一个字符,因为您 * 告诉它忽略 * 输入中的字符......调用
cin.ignore()
。该调用不在循环 * 内部 ,而是在循环之前,以便忽略cin >> number
提取后留在输入流中的换行符。注意,对
getline
的调用不会在流的缓冲区中留下换行符;参见this cppreference page:......下一个可用输入字符是
delim
,如Traits::eq(c, delim)
所测试的,在这种情况下,从输入中提取定界符字符*,但不将其附加到str
。下面是经过适当修改的代码版本: