【问题标题】:Finding all the correct and incorrect characters in an array查找数组中所有正确和错误的字符
【发布时间】: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


【解决方案1】:

并非您的函数f1 的所有代码路径都返回一个值;实际上你的编译器应该告诉你这个。因此,如果找不到您的角色(即循环结束),那么函数将返回的内容是未定义的(行为)。如果它返回true,那么这就是您正在观察的行为。但是请注意,在这种情况下,该函数可能会返回任何内容,因此您不能依赖这种行为。

bool f1(char x)
{
    int i;
    for (i = 0; i < 10; i++) {
        if (x == word[i]) {
            return true;
        }
    }
    return false;
}

它应该可以工作。

顺便说一句:请注意,C 函数 strchr 提供了非常相似的功能(尽管它仅适用于 0 终止的字符串)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-17
    • 1970-01-01
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 2017-01-02
    • 1970-01-01
    相关资源
    最近更新 更多