【发布时间】:2020-06-11 05:45:56
【问题描述】:
我正在做一些代码检查 word 是否在 ignoreWords 数组中。即使某些单词在 ignoreWords 数组中,该函数也会继续为第一个值返回 true,然后为其余元素返回 false。我不确定自己做错了什么,如果有任何帮助或建议,我将不胜感激。
bool isIgnoreWord(string word, string ignoreWords[])
{
int length;
string copy[length];
for(int i=0; i < length; i++){
copy[length] = ignoreWords[i]; //to find out length of ignoreWords
//cout << copy[length] << endl;
if(copy[length] == word)
return true;
else
return false;
}
//function returns whether word is in the ignoreWords array
}
编辑:修复它。我把它弄得比实际复杂得多。这是有效的代码:
bool isIgnoreWord(string word, string ignoreWords[])
{
for(int i=0; i < 50; i++){
if(ignoreWords[i] == word){
return true;
}
}
return false;
//function returns whether word is in the ignoreWords array
}
【问题讨论】:
-
如果你没有初始化长度,你怎么能有copy[length]?
-
我实际上对此感到困惑。我想初始化长度,因为我没有明确告诉我长度有多长......我的解决方案是复制长度以忽略单词来找出长度。很确定这是一种糟糕的方法
-
另外请给出一个最小的可重现示例。顺便说一句,您使用的可变长度数组仅是 C,而不是标准 C++。