0

I am trying to check to see if the users input is equal to "l". I should be getting "test worked" to the console when I press "l" and then enter, but I am not.

Here is my C++ code

char userIn[8];
std::cin >> userIn;
if (userIn == "l") {
    std::cout << "test worked";
}
cigien
  • 57,834
  • 11
  • 73
  • 112

3 Answers3

1

What is the type of userIn? If it is char then you must use single quotes('') to check the values. Otherwise double quotes('')

char userIn;
std::cin >> userIn;
if (userIn == 'l') {
    std::cout << "test worked";
}
  • 1
    Please see the edit to the question. `userIn`'s type is defined. –  Dec 07 '20 at 02:08
  • userIn is being defined as a char, it has nothing in it until the user gives an input –  Dec 07 '20 at 03:01
1

to make it work the way I wanted i had to change it to

char userIn[8];

std::cin >> userIn;
if (*userIn == 'l') {
    std::cout << "test worked";
}
else {
    std::cout << userIn;
}
  • Keep in mind that you should probably check that `std::cin` is still in a good state, and you should also check the length of `userIn` before dereferencing the first character like this. – Mooing Duck Dec 07 '20 at 02:40
  • I see you've posted a self-answer. Thanks. I can't tell from your question if the user input will always be a single character, or if you only want to compare the first character to `'l'`. Can you edit the question to clarify that please? – cigien Dec 07 '20 at 02:44
  • 1
    This code is comparing only the 1st character of the user’s input. If the user inputs anything that begins with `l` this code will test as true. – Remy Lebeau Dec 07 '20 at 02:45
1

You are comparing a char[8] to a const char[2]. Both decay into pointers to their 1st elements. So you are comparing pointers, not content. And the two are located at different memory addresses, so the pointers compare as false.

Change your char[] to std::string, which has an operator== implemented:

std::string userIn;
std::cin >> userIn;
if (userIn == "l") {
    std::cout << "test worked";
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • thanks, for what I am doing right now I only care about having a single letter input, some people have posted answers for multiple letters and that will probably be useful for me in the future. –  Dec 07 '20 at 02:57
  • 2
    @Rockyroad000 “*I only care out having a single letter input*” - then why are you declaring `userIn` as a `char[8]` array and not as a single `char`? – Remy Lebeau Dec 07 '20 at 03:44