[英]Character count ignoring first characters in multiple strings
#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";
}
}
我正在尝试计算多个字符串中元音和辅音的数量,但出于某种原因,它只为第一个字符串提供正确的 output。
我注意到,对于下一个字符串(第二个、第三个等等),它不计算字符串的第一个字母。 为什么是这样?
该代码忽略了第一个字符串之后的每个字符串的第一个字符,因为您告诉它忽略输入中的那些字符……通过调用cin.ignore()
。 该调用不应在循环内,而应紧接在循环之前,以便忽略cin >> number
提取后留在输入 stream 中的换行符。
请注意,对getline
的调用不会将该换行符留在流的缓冲区中; 请参阅 此 cppreference 页面:
…下一个可用的输入字符是
delim
,正如Traits::eq(c, delim)
测试的那样,在这种情况下,分隔符是从 input 中提取的,但没有附加到str
。
这是您的代码的适当修改版本:
#include <string>
#include <iostream>
using std::cin, std::cout;
int main()
{
std::string sentence;
int countv = 0, countc = 0, countspace = 0, number, s = 1;
cout << "How many sentence would you like to check? - ";
cin >> number;
cin.ignore(); // Call ignore HERE (once) to skip the newline left in the buffer from the above!
while (s <= number)
{
cout << "\nSentence " << s << ":";
// cin.ignore(); WRONG!
std::getline(cin, sentence);
for (size_t 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 = countv = countspace = 0; // Nicer than the dodgy use of the comma!
s++;
cout << "\n";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.