Matthew Lueder Matthew Lueder - 1 year ago 73
C++ Question

How to compare user input (from std::cin) to a string?

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:


Why does the if statement evaluate as

Answer Source
  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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download