簡體   English   中英

字符計數忽略多個字符串中的第一個字符

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM