1
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    string codigo = "12345678917";
    int remainder = 7;
         

    
    if (remainder == codigo[10]) { 
        cout<<"equal" << endl;
    }
    return 0;
}

It's just a simple comparison. This code doesnt print "equal".

I changed the type of the int to char or string but it didnt work. I tried comparison methods and still nothing. Am missing something here?

It did work when i changed remainder to '7'. But idk why comparing with variable doesnt work

1 Answers1

2

in your code you are comparing an int to a char, in this situation there will be an implicit conversion from char to int.

using

cout << "int value: " << (int)codigo[10] << endl;

you can see that the int value of the character is 55, as 7 does not equal 55 the condition will not be true. It also won't work if you just change the type to char as this will cast 7 to a char which is not the character '7'.

Using single quotes around the 7 causes the value to be a character literal, as it is stored in an int its value will be 55. Since this is equal to the character value of codigo[10] the condition will be true.

White Wizard
  • 608
  • 3
  • 19
  • 1
    Side note: on some increasingly unusual systems you wont get 55 for the encoded value of '7', but the end result will be the same. You cannot place '7' at encoding 7 because that would mean you have to put '0' at encoding 0, and 0 is reserved for the null character used to terminate c-style strings. – user4581301 Nov 19 '22 at 02:39