4

So this one sounds very easy but I am getting some strange behavior.

In my program there is the following code:

std::cout << "Would you like to generate a complexity graph or calculate global complexity? (graph/global)\n";
char ans[6];
std::cin >> ans;

if (ans != "global") std::cout << ">>" << ans << "<<" << std::endl;

When I run my program and type in "global" when I'm prompted for input, the program returns:

>>global<<

Why does the if statement evaluate as true?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Matthew Lueder
  • 953
  • 2
  • 12
  • 25

2 Answers2

3
  1. You should use strcmp or strncmp for comparison of c-style strings. ans != "global" is just comparing the memory address pointed by the pointer, not the content of string.

  2. char ans[6]; should be char ans[7];, for "global", you need one more char for the terminating null character '\0'.

You should use std::string instead, to avoid such issues.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
0

You declared ans as array of char, thus if if (ans != "global") expression, ans means pointer to the beginning of the string. So you compare two pointers which are obviously not equal and your expression evaluates to true. If you still want to declare ans as a C-style string, you may construct an std::string from it before comparing:

if (std::string(ans) != "global") {......}

Or just declare ans as std::string instead of char[].

Sergey
  • 7,985
  • 4
  • 48
  • 80