C++ if statements using strings not working as intended

前端 未结 4 991
名媛妹妹
名媛妹妹 2020-12-06 21:38

I have searched for this error but noone seems to be having the same problem as me. I am trying to make a basic text based RPG game in C++ to learn, and I want the user to b

相关标签:
4条回答
  • 2020-12-06 22:25

    You need to do current_move==string("attack") otherwise you will be comparing pointers. String operator == or strncmp, either one or the other...

    0 讨论(0)
  • 2020-12-06 22:32

    Your problem is that you are comparing C strings. When you do == on them, you are comparing the pointer of the two, which in this code is useless to do.

    My suggestion would be to just change the type of current_move to std::string and it will just work. Then you will be comparing the contents, not the pointers.

    0 讨论(0)
  • 2020-12-06 22:34

    If you're using a C string (char[]), you need to use strcmp() to compare it. If the two strings are equivalent, it will return 0.

    if (strcmp(current_move, "ATTACK") == 0) will return true if they match.

    0 讨论(0)
  • 2020-12-06 22:35

    What's the type of current_move? If it's char* (or char[]), you are comparing pointers, not strings. Better use std::string for current_move, then the comparison with == will work intuitively.

    You need to add #include <string>. (In MSVC certain parts of strings also work without that, but it's nonstandard and leads to errors e.g. when passing strings to cout).

    0 讨论(0)
提交回复
热议问题