c++ 字符计数忽略多个字符串中的前几个字符

hmae6n7t  于 2022-12-30  发布在  其他
关注(0)|答案(1)|浏览(154)
#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";
    }
}

我试图计算多个字符串中元音和辅音的数量,但是由于某种原因,它只给出了第一个字符串的正确输出。
我注意到,对于接下来的字符串(第二个,第三个等等),它不计算字符串的第一个字母,这是为什么?

t8e9dugd

t8e9dugd1#

代码 * 忽略 * 每个字符串后面的第一个字符,因为您 * 告诉它忽略 * 输入中的字符......调用cin.ignore()。该调用在循环 * 内部 ,而是在循环之前,以便忽略cin >> number提取后留在输入流中的换行符。
注意,对getline的调用不会在流的缓冲区中留下换行符;参见this cppreference page
......下一个可用输入字符是delim,如Traits::eq(c, delim)所测试的,在这种情况下,从输入
中提取定界符字符*,但不将其附加到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";
    }
}

相关问题