If语句未能激活
If statement failing to activate
我想创建一个函数,应该做以下事情:
-取两个字符数组,一个比另一个小,并确定较小的字符数组是否是较大数组的子集。举个例子:阵列A: {"s","c","h","o","o","l"}
;阵列B: {"c","h"}
。我必须使用指针自增/自减操作。这是我生成的代码:
int locator(char *Bigptr, char *Smallptr) {
int count = 0;
for (; *Bigptr != ' '; Bigptr++) {
if (*Smallptr == *Bigptr) {
for (; (*Smallptr == *Bigptr) != ' '; Smallptr++, Bigptr++) {}
if (*Smallptr == ' ') {
return count;
}
else {
cout << "small is not the subset of big" << endl;
return 0;
}
}
count++;
}
return 0;
我认为代码应该是这样运行的:
两个指向字符数组的指针作为函数'locator'的形参。变量count是我为了告诉我A中出现的第一个字符的下标是什么而放置的(例如:"school"answers"ch"是元素1,所以A[1])。第一个for循环确保较大数组的第一个值是一个实际字符。if语句在发现一个共同字符时返回true。然后,第二个for循环检查是否所有较小的数组都存在于较大的数组中。当我的程序编译时,所有这些都按预期工作。嵌套的if语句出现问题。如果小数组是大数组的子集,我期望它是成立的。为什么不是这样呢?以"school"answers"ch"为例。*Smallptr最初指向数组B的第一个元素(即:"ch"),所以是"c"。然后将其与"学校"中的"c"进行比较。然后对两个指针进行自增,使它们都指向各自数组中的"h"。同样,它们再次递增,使*Bigptr指向"0",*Smallptr指向" "。事实并非如此吗?为什么函数总是输出else语句?
你对第二个for
循环的理解是错误的。
if (*Smallptr == *Bigptr) {
for (; (*Smallptr == *Bigptr) != ' '; Smallptr++, Bigptr++) {}
由于您已经确定(在if
条件下该语句)*Smallptr == *Bigptr
,该比较给出了非零(true
)结果。
测试(*Smallptr == *Bigptr) != ' '
将非零结果与值为零的char
进行比较。非零值永远不会比较为零(至少,不包括bool
在内的标准整型),因此循环不起作用。
符合描述的循环是
for (; (*Smallptr == *Bigptr) && *SmallPtr != ' '; Smallptr++, Bigptr++) {}
检查两个字符是否相等,且都非零。
考虑到这是c++,您可能希望利用标准库中已经存在的功能。我要按这个顺序做:
bool is_subset(std::string big, std::string small) {
std::sort(big.begin(), big.end());
std::sort(small.begin(), small.end());
std::string result;
std::set_difference(small.begin(), small.end(),
big.begin(), big.end(),
std::back_inserter(result));
return result.empty();
}
这不能满足使用指针的要求,但在我看来,这是一种更好的方法。
for (; (*Smallptr == *Bigptr) != ' '; Smallptr++, Bigptr++) {}
是不正确的
你需要的是:
for (; (*Smallptr == *Bigptr) && *SmallPtr != ' '; Smallptr++, Bigptr++)
{
++count;
}
你有几个地方错了。看看这个返工:
int locator(char *Bigptr, char *Smallptr) {
int count = 0;
for (; *Bigptr != ' '; Bigptr++) {
if (*Smallptr == *Bigptr) {
for (; *Smallptr == *Bigptr && *Bigptr!=' '; Smallptr++, Bigptr++) {
count++;
}
if (*Smallptr == ' ') {
return count;
}
break; //this is necesary in order not to stay in the main for loop
}
}
std::cout << "small is not the subset of big" << std::endl;
return count;
}
EDIT:在main函数中测试代码,它工作得很好:
int main(int argc, const char * argv[]) {
std::cout << locator("hello","ohl"); //this prints "small is not the subset of big"
std::cout << locator("hello","ell"); //this prints "3" (the count of matching characters)
return 0;
}
- 我的简单if-else语句是如何无法访问的代码
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- 为什么是0;C++中的有效语句
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 是否可以使用if constexpr删除控制流语句
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 我似乎对if/else的基本语句有问题:/
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- If语句在c++中被忽略
- 比较if语句中的数组值和int值
- 以在Qt中的IF语句中设置时间延迟
- Craps游戏问题,忽略if语句
- "类模板示例<int>;"语句对 C++11 是什么意思?
- 如何编写一个使用n倍三元条件语句的C++布尔函数
- 使用条件语句激活函数的目的是什么
- If语句未能激活