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

So that sounds very simple, but I get weird behavior.

My program has 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 "global", when I am prompted to enter it, the program returns:

>>global<<

Why is the if statement evaluated as true?

+4
source share
2 answers
  • You should use strcmpor strncmpto compare c-style strings. ans != "global"just compares the memory address indicated by the pointer, not the contents of the string.

  • char ans[6];must be char ans[7];, for "global"you need another one charfor the terminating null character '\0'.

std::string, .

+2

ans char, if (ans != "global"), ans . , , , true. ans C-, std::string :

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

ans std::string char[].

0

Source: https://habr.com/ru/post/1654299/


All Articles