【发布时间】:2018-12-30 16:32:18
【问题描述】:
我正在编写一个代码,我想检查任何输入的字符值是否属于上面的数组。如果它没有字母,我想将 +1 添加到 e。这是我的代码:
#include <iostream>
using namespace std;
char word[10] = { 'H', 'o', 'u', 's', 'e' };
bool f1(char x)
{
int i;
for (i = 0; i < 10; i++) {
if (x == word[i]) {
return true;
}
}
}
int main()
{
char x;
int e = 0, k = 1;
while (k <= 10) {
cin >> x;
if (f1(x) != true)
e++;
k++;
}
cout << e << endl;
return 0;
}
我的问题是结果是 e=0 或 e=10,我输入了数组中的字符,反之亦然。
任何帮助将不胜感激。
【问题讨论】:
-
如果找不到字符,那么
f1会返回什么? -
你的函数
f1()暴露了未定义的行为(你应该得到一个编译器警告)。并非所有代码路径都返回值。 -
开启编译器警告。那会指出问题所在。
-
return false;不隐含在f1()的末尾,必须在for 后面加上 -
[...] Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function. [...]
标签: c++ arrays visual-c++ logic