简体   繁体   中英

Logical operators with class/objects in C++

Completely new to C++. Trying to understand classes and objects, so far I get the gist of it, as it's nothing too complicated for the very basics. However, this code I have wrote is not working as intended. It works somewhat, however it asks for user input twice.

#include <iostream>
#include <string>
using namespace std;

class FooFoo {
public :

string GetName() {
    cin >> name;
    return name;
}

private:
    string name;
};

int main()
{
FooFoo object;
if (object.GetName() == "John" || object.GetName() == "Chris")
{
    cout << "Yes";

}
else {
    cout << "No";
}

}

If I input "John", it will return yes right away. However, when I input anything else, it will prompt me to enter something again, and then the if/else acts accordingly to whatever I inputted.

You call object.GetName() twice which causes the input to be asked for twice. Store the result of this function to a variable and use that in the if statement. The || statement is short-circuited if the first expression is true. This leads to the second call not being executed if the first is true.

That is because GetName() is asking for input every time,

So the first time it is asking for x, if x isnt john it goes to the next test, which then gets input and tests that against x = chris.

try changing it to this:

int main()
{
FooFoo object;
string test = object.GetName()
if (test == "John" || test == "Chris")
{
    cout << "Yes";

}
else {
    cout << "No";
}

}

Hope that helps

Your current if statement effectively evaluates to:

if (object.GetName() == "John")
  cout << "Yes";
else if (object.GetName() == "Chris")
  cout << "Yes";
else
  cout << "No";

Try entering Chris followed by John and you should get No .

Just call getName() before the if statement, store the value in a local variable, then test that instead:

string name = object.GetName();
if (name == "John" || name == "Chris")
  cout << "Yes";
else
  cout << "No;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM