【问题标题】:if (aCHAR == 'character' || 'another character') problemsif (aCHAR == 'character' || 'another character') 问题
【发布时间】:2011-08-16 15:50:42
【问题描述】:

嗨,所以我正在尝试检查字符串中的某个字符以确保它不是 \、=、| 等,如果不是,则用“播放器”字符替换空格,但函数返回 true每次,即使 char newLoc 等于 ''(空):

screen.get_contents 返回一个充满字符串的向量容器,并且
sprite.get_location 返回一个int数组,有两个数字,[0]代表X,[1]代表Y。

bool check_collision(Sprite& sprite,int X, int Y, Screen& screen) 
    {
    ////////////////////// check whats already there /////
        char newLoc = screen.get_contents(sprite.get_location()[0]+Y,sprite.get_location()[1]+X);
        if (newLoc == '|' || '/' || '_' || '=' || 'X' || 'x' )
            return true;
        else
            return false;
    };

有什么问题? 谢谢!!

【问题讨论】:

    标签: c++ char boolean


    【解决方案1】:

    你需要:

    if (newLoc == '|' || newLoc == '/' || ...)
    

    你写的相当于:

    if (newLoc == ('|' || '/' || ...))
    

    相当于:

    if (newLoc == 1)
    

    请注意,更简洁的写法可能是:

    switch (newLoc)
    {
    case '|':
    case '/':
    ...
        return true;
    
    default:
        return false;
    }
    

    【讨论】:

    • 谢谢!但是IDE为什么要出1??
    • @Griffin: ||逻辑或运算符。如果它的任何一个参数是TRUE,那么它“返回”TRUE。字符文字的计算结果为 TRUE,除非它是空字符 '\0'。所以表达式的 RHS 等于TRUE。当解释为整数值时,这反过来计算为1
    【解决方案2】:
    newLoc == '|' || '/' || '_' || '=' || 'X' || 'x'
    

    不起作用,你必须这样做:

    newloc == '|' || newloc == '/' || etc...
    

    但是这更容易阅读:

    switch (newloc):
        case '|':
        case '/':
        case '_':
        case '=':
        case 'X':
        case 'x':
            return true;
        default:
            return false;
    

    【讨论】:

      猜你喜欢
      • 2021-10-02
      • 1970-01-01
      • 2014-09-27
      • 2022-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-17
      • 1970-01-01
      相关资源
      最近更新 更多