Results 1 to 4 of 4

Thread: Need help with c++ string array handling with function

  1. #1
    Join Date
    Dec 2012
    Beans
    1

    Exclamation Need help with c++ string array handling with function

    Hello Experts,
    I need a little help from you??
    Code:
    #include<iostream>
    #include<string.h>
    using namespace std;
    
    string *playerName()
    {
        string player[2];
        cout<<"\nWelcome to BlackJack Lite!.\n**************************\n";
        cout<<"Enter The Name of Player1 :\n ";
        getline (cin, player[0]);
        cout<<"Enter The Name of Player2 :\n ";
        getline (cin, player[1]);
        return player;
    }
    
    int main()
    {
        int dealer=0, result[2]={0,0};
        string *player=playerName();
        cout <<"player 1 is: "<<player[0]<<"player2 is: "<<player[1];
        return 0;
    }
    
    Warning : address of local variable 'player' returned
    I don't understand why this code is not working

  2. #2
    Join Date
    Nov 2007
    Location
    Nantes (France)
    Beans
    72

    Re: Need help with c++ string array handling with function

    Your strings just exist during the playerName() function execution. Their address is not anymore valid when the function returns.
    You should use something like:
    string *player = new string[2];

  3. #3
    Join Date
    Jun 2007
    Location
    Waikikamukau, New Zealand
    Beans
    Hidden!
    Distro
    Ubuntu

    Re: Need help with c++ string array handling with function

    Thread moved to Programming Talk.
    Forum DOs and DON'Ts
    Never assume that information you find using a search engine is up-to-date.

  4. #4
    Join Date
    Jun 2007
    Location
    Maryland, US
    Beans
    6,248
    Distro
    Kubuntu

    Re: Need help with c++ string array handling with function

    It's rare that one needs to allocate an STL container.

    Consider the following:
    Code:
    #include <string>
    #include <iostream>
    
    using namespace std;
    
    string getStrInput(const char* prompt)
    {
        string str;
    
        cout << prompt << ": ";
        getline(cin, str);
    
        return str;
    }
    
    int main()
    {
        cout << "\nWelcome to BlackJack Lite!.\n**************************\n";
        string player1 = getStrInput("Enter the name of player1");
        string player2 = getStrInput("Enter the name of player2");
        //...
    }
    P.S. If you require an array of "something", declare an STL vector.
    Last edited by dwhitney67; December 23rd, 2012 at 01:18 PM.

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •