簡體   English   中英

字符串中的C ++元音,禁止比較

[英]C++ Vowels in string, comparison forbidden

我正在嘗試計算字符串中元音的總數。 我使用strlen來獲取字符串的總長度,但是當我嘗試通過每個字母對字符串進行計數時,它說C ++禁止比較。 所以我假設我的if語句出了問題。

#include <iostream>
#include <cstring>
using namespace std;


int main() {

    char sentence[] = "";
    int count;
    int total;
    int length;
    int lengthcount;
    int output;
    output = 0;
    length = 0;
    count = 0;
    total = 0;
    cin >> total;

    while (total != count){
        cin >> sentence;
        length = strlen(sentence);
        while (length != lengthcount)
            if (sentence[length] == "a" ||sentence[length] == "e"||sentence[length] == "i"||sentence[length] == "o"||sentence[length] == "u"||sentence[length] == "y"){
             ++ output;
             ++ lengthcount;
                 else{
                ++lengthcount;
             }
            }
        ++count;
    }

return 0;
}

sentence[length]是單個字符。 應該將其與'a'而不是"a"

"a"是字符數組,不支持與內置operator==直接比較。

sentence[index] == 'a'; // where index is probably lengthcount in your example

應該做到的。 如果使用std::string是一個選項,則應優先使用char數組。

另外,您的char sentence[] = ""; 不僅需要'\\0'字符,還需要更多空間。 一些替代方法包括將std::stringstd::getlinechar[nnn]cin.get(...)一起使用,以確保您不會溢出分配的緩沖區。

有關主要問題之一,請參閱Nialls答案。

代碼的算法問題再次出現在if語句中。

sentence[length]返回您的c_string的最后一個字符(在這種情況下,為終止該字符串的空字符'/0' )。

您的if語句應更像:

if (sentence[lengthcount] == 'a'\
  ||sentence[lengthcount] == 'e'\
  ||sentence[lengthcount] == 'i'\
  ||sentence[lengthcount] == 'o'\
  ||sentence[lengthcount] == 'u'\
  ||sentence[lengthcount] == 'y')
{
    \\do something
}

請記住也為字符串預分配空間,即

char sentence[50];

這將為您提供49個字符+終止符的空間。 或者,使用std::string

如果您希望計算給定字符串中的元音總數,則需要使用sentence[lengthcount] 可以說sentenceabc strlen(sentence)將返回3,並且由於在c ++中,索引以0而不是1開頭,因此句子[length]將檢查'\\ 0',因此在整個循環中您都要檢查最后一個值'\\ 0'是沒有意義的。 另外,不要忘記初始化lengthcount。 休息所有提及的事情。

char句子[] =“”產生長度為1的數組句子。

cin >>句子不能很好地工作,是不是如果句子不能包含多個字符並且尾隨nul字節已經需要一個字符?

lengthcount是一個單位化的變量,其余的代碼只會讓我頭疼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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