logo elektroda
logo elektroda
X
logo elektroda

[C++] Determine Gender Based on First Name: Analyzing Last Character in a Char String

toma5z 23737 5
ADVERTISEMENT
Treść została przetłumaczona polish » english Zobacz oryginalną wersję tematu
  • #1 7521095
    toma5z
    Level 13  
    Hello,
    I have been dealing with the basics of programming for a long time (pascal, java, c / c ++).

    One exercise bothers me.

    I want to write a program where the user gives the first name.
    The program checks the string of characters and determines whether you are a man or a woman.

    In terms of theory, it would rather look like this:
    We assume a string string name [15]
    we get the name with cin stream.
    When the last letter of the name is "a" in the conditional instruction, gender-female is displayed on the screen, otherwise gender-male, exception: male-male name.

    And here's my question, how do I check the last character of the char string?

    I know, these are the basics, as of today I am helpless ...

    I am asking for tips, help.
  • ADVERTISEMENT
  • Helpful post
    #2 7521305
    FirstStep
    Level 12  
    You're a bit confused.
    string imie[15]
    is a 15-element array of strings (i.e. an array of 15 words). And the array char name [15] is one string (that is, one word).

    How do I find the last letter? Very simply, each word loaded into the array ends with the character '\ 0', so we need the penultimate element.
    [code:1:851f968178]
    #include

    using namespace std;


    int main()
    {
    char imie[15];
    cout imie;

    char znak_konca= '\0';
    //sprawdzenie czy kuba?
    if(imie[0]=='k' && imie[1]=='u' && imie[2]=='b' && imie[3]=='a')
    {
    cout
  • ADVERTISEMENT
  • #3 7522373
    toma5z
    Level 13  
    Ok, thanks a lot for your help.
    Yes you are right it has to be char - a string, not a string.

    I'm just still considering a solution through strlen


    if ((imie [strlen(imie)-1]=='a' ) && (strcmp (imie,"Kuba"))!=0)
  • ADVERTISEMENT
  • #4 7522882
    Mari@@@n
    Level 19  
    The name Kuba is a kind of diminutive of the name Jakub, so the algorithm does not have to be an exception in this case. But that's a bit off topic.
    Regards
  • ADVERTISEMENT
  • Helpful post
    #5 7525032
    Dariusz Bismor
    Level 18  
    Well no - it doesn't have to be a char array - as long as it is to be done in C ++! Everything is easier in C ++:
    [code:1:1ebfb3b875]string imie;
    cout > imie;
    if( imie == "Kuba" ){
    cout
  • #6 7526963
    toma5z
    Level 13  
    Thanks, I modified your program and I have something like this:


    [code:1:1a98bceb00]
    ...
    if( (imie[imie.size()] == 'a') && (imie != "Kuba") )
    cout
ADVERTISEMENT