为什么字符串中的每个字符都不等于等效字符
Why does each single character of the string not equal to the character equivalent?
我试图检查字符串数组中字符串的每个字符是否等于五个元音中的任何一个。然而,当我测试字符串中的元音字符何时等于"元音"时,我发现它们不相等。代码的问题是下面粗体部分。此外,当我尝试执行"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') {
相关文章:
- 为什么 std::round(sin(pi/6)) 不等于 1?
- 为什么当我从 cin 阅读时转义字符不起作用?
- 你怎么编码,如果x不等于一个数字,程序就会退出
- u张量模型输出不等于预期输出
- 虽然不等于陈述和/或差异
- 这种关系不等于定义良好的表达式吗?
- 为字符串中的每个字符(不是字符位置!)分配唯一的索引
- OpenGL 版本不等于支持的着色器版本
- 两个 4 位位字段加起来不等于一个字节的大小 - 如何修复?
- 如果整数不等于 0,则将其减小为 1
- C 循环虽然不等于任何两个值
- vb.net单不等于c float
- 如何获取C编译器#Error如果大小(struct ..)不等于给定的数字
- C++ 而语句不等于检查
- C++:将 int 转换为字符不会产生正确的值
- 使用scanf()在数组中获取字符(不与空格分开)
- C++ 错误:与调用<类构造函数(字符*&、字符*&、字符*&、字符*&)不匹配
- 读取字符,如果不等于 ا,则将其品脱
- 为什么字符串中的每个字符都不等于等效字符
- 在c++中,不等于(!=)运算符不能正确使用字符