Home > Mobile >  How to access the second last element of a string
How to access the second last element of a string

Time:12-06

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!

CodePudding user response:

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.

  • Related