如果总是返回true [英] If always returns true

查看:121
本文介绍了如果总是返回true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是尝试了一下C ++,但我无法弄清楚为什么两个if语句都返回true:

I'm just experimenting a bit with C++ but I can't figure out why both if-statements return true:

#include <iostream>
#include <windows.h>
using namespace std;

int main()
{
    cout << "Language?" << endl;
    string lang;
    cin >> lang;
    if(lang == "Deutsch" || "deutsch")
    {
        cout << "Hallo Welt!";
    }
    else
    {
        return false;
    }
    if(lang == "English" || "english")
    {
        cout << "Hello World!";
    }
    else
    {
        return false;
    }
    return 0;
}

我对C ++和stackoverflow很陌生,所以我很抱歉,如果这是一个愚蠢或经常被问到的问题,但我真的不知道。请帮忙!

I'm pretty new to C++ and stackoverflow so I'm sorry if that's an stupid or frequently asked question but I really don't know any further. Please help!

推荐答案

 lang == "Deutsch" || "deutsch"

错误

lang == "Deutsch" || lang == "deutsch"

是对的

deutsch单独返回内存中字符串的地址。这是
总是不等于零。这意味着真的。

"deutsch" alone returns the address of the string in memory. which is always not equal to zero. which means true.

a == "hello" || "bob"

表示

(a == "hello") || "bob"

无论 a ==hello结果(true或false), false || bob变为 false ||指向bob的指针。所有非空指针都是 true ,所以这是 false || true true

regardless of what a == "hello" results in (true or false), false || "bob" becomes false || pointer to "bob". All non-null pointers are true, so this is false || true which is true.

#include <iostream>
#include <windows.h>
using namespace std;

int main()
{
    cout << "Language?" << endl;
    string lang;
    cin >> lang;
    if(lang == "Deutsch" || lang == "deutsch")
    {
        cout << "Hallo Welt!";
    }
    else
    {
        return false;
    }
    if(lang == "English" || lang == "english")
    {
        cout << "Hello World!";
    }
    else
    {
        return false;
    }
    return 0;
}

这篇关于如果总是返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆