1

this is a function that checks if a person is a man or a woman by checking the second

last element of his social security number. If the number is even then the person is a

woman. If odd then a men. The code is working in a strange way. Sometimes it does the job

and sometimes not. this is the code:

char check_gender(string person_nummer){
    int check_digit = (person_nummer.back() - 1) - '0'; 
    char gender; 
    if(check_digit % 2 == 0){
        gender = 'K';     // K for a women(kvinna in swedish)
    }
    else{
        gender = 'M';     // M for man
    }
    return gender;
}
int main(){
  string number; 
  cout << "enter number" << endl; 
  cin >> number; 
  cout << check_gender(number) << endl; 
  return 0; 
}

input1: 8602024898

output1: M // correct output

input2: 8510309159

output1: K // wrong output

input3: 7102022980

output M // wrong output

input4: 4906147410

output M // correct output

weird!

1
  • Have you tried stepping through the code with a debugger?
    – Quimby
    Commented Dec 5, 2022 at 10:59

1 Answer 1

3

This returns the last character in the string:

person_nummer.back()

you then subtract 1 from it. That means, if the last character is '9', you now have '8'.

To get the second last character, you need;

person_nummer[person_nummer.size() - 2]

This will give the correct output for your example numbers: Demo

Getting the second last character using iterators:

*std::prev(person_nummer.cend(), 2)

Demo

or reverse iterators:

*std::next(person_nummer.rbegin())

The code is working in a strange way. Sometimes it does the job and sometimes not.

You will get a number by doing person_nummer.back() - 1 but it's a 50/50 chance that it'll be correct for the entered person_number. The last digit is a check digit and has nothing to do with the gender but you were using it to determine gender.

12
  • *(person_nummer.cend() - 2) - '0' should work fine as well if OP wants iterator semantic instead Commented Dec 5, 2022 at 10:46
  • @TheDreamsWind Yes, or *std::prev(person_nummer.cend(), 2) - '0'.
    – Ted Lyngmo
    Commented Dec 5, 2022 at 10:47
  • @TheDreamsWind now the output is 'k' for all input so it's not working at all
    – sam
    Commented Dec 5, 2022 at 10:49
  • @sam I added a demo where you can see that it does the correct thing.
    – Ted Lyngmo
    Commented Dec 5, 2022 at 10:54
  • 1
    @TedLyngmo yeah I can see it now. thanks again
    – sam
    Commented Dec 5, 2022 at 11:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.