为什么字符串中的每个字符都不等于等效字符

Why does each single character of the string not equal to the character equivalent?

本文关键字:字符 不等于 字符串 为什么      更新时间:2023-10-16

我试图检查字符串数组中字符串的每个字符是否等于五个元音中的任何一个。然而,当我测试字符串中的元音字符何时等于"元音"时,我发现它们不相等。代码的问题是下面粗体部分。此外,当我尝试执行"a"||"e"||"I"||"o"||"u"时,我会得到一个错误,即ISO C++禁止在指针和整数之间进行比较。我怎样才能检查它们是否相等?谢谢你抽出时间。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <cmath>
#include <cstdlib>
using namespace std;
int l, c; //l is amount of letters in password, c is amount of letters being inputted
char letters[1000000]; //the letters being inputted
vector <string> pass; //string vector of the stored passwords
void rec(string current, int index, int x){ //determining all possible passwords
    if (index >= 4){
        pass.push_back(current);
    }
    else{
        for (int i=0; i<c; i++){
            if (x<i){
                int old;
                old = x;
                x = i;
                rec(current + letters[i], index+1, x);
                x = old;
            }
        }
    }
}
int main (int argc, char ** argv)
{
    cin >> l >> c;
    int x = -1;
    for (int i=0; i<c ;i++){
        cin >> letters[i];
    }
    sort(letters, letters + c); //sorted from least to greatest
    rec("", 0, x);
    for (int i=0; i<pass.size(); i++){
        int vl=0; //number of vowels
        int nvl=0; //number of non-vowels (consonants)
        for (int j=0; j<l; j++){
            **if (pass.at(0)[j] == 'a' || 'e' || 'i' || 'o' || 'u'){**
                vl++;
            }
            else{
                nvl++;
            }
            if (j == l-1){
                if (vl >= 1 && nvl >= 2){
                    cout << pass.at(0) << endl;
                }
            }
        }
    }
    return 0;
}

在C++中,X || Y表示:

  • 测试X是否为真。若是,则整个表达式的结果为true
  • 否则,测试Y是否为真。CCD_ 5的结果是表达式的结果

所以你的代码:

pass.at(0)[j] == 'a' || 'e' 

(暂时省略i等,因为它们不会改变任何内容)。

我们测试了CCD_ 7。这是错误的,所以现在我们测试'e'。并不是说你没有测试pass.at(0)[j] == 'e'。您刚刚测试了'e'。这与测试'e' != 0是一样的,这是真的。因此,此时表达式的求值结果为true(并且不检查'i'等)

您可能打算测试pass.at(0)[j]是否包含'a''e'等值中的任何一个。如果是,那么编码的一种方法是:

if ( std::strchr("aeiou", pass.at(0)[j]) )

不过,在执行此操作之前,您应该确保j < strlen(pass.at(0));使用CCD_ 18生成越界索引会导致未定义的行为。

因为您使用了错误的||||两边的部分本身就是一个"真或假"表达式,所以你需要这样的东西:

if (pass.at(0)[j] == 'a' || pass.at(0)[j] == 'e' ... )

否则,表达式始终为true,因为如果左侧或右侧的表达式为true,则||为true,而'e'不为零则为true。

这并不像你想的那样。。。

(pass.at(0)[j] == 'a' || 'e' || 'i' || 'o' || 'u')

你需要明确比较,

char t = pass.at(0)[j];
if (t == 'a' || t == 'e' || t == 'i' || t == 'o' || t == 'u') {