Functions with strings as parameters.

Hello guys. I'm trying to do a program that asks for names for a couple of players of a certain game. I write the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <cstdlib>
#include <iostream>

using namespace std;

void ask_for_names (string Jugador_1, string Jugador_2);

int main(int argc, char *argv[])
{
    
    string J1="xxx", J2="yyy";
    
    ask_for_names (J1, J2);
    
    cout<<J1<<" and "<<J2<<endl;
    
    
    system("PAUSE");
    return EXIT_SUCCESS;
}

void ask_for_names (string player_1, string player_1)
{
    string saux1="XXX", saux2="XXX";
     
    cout<<"Name for player 1: \n";
    cin>>saux1;
    player_1=saux1;
    
    cout<<"Name for player 2: \n";
    cin>>saux2;   
    player_1=saux2;  
}


and when I compile it, everything goes well (It asks for the names) but it doesn't print the names I have just entered. Insteda it just prints

xxx and yyy


What is wrong?

Thank you for the help!
sorry guys, theres a mistake: line 32 was suposed to be "player_2=saux2;". Same result.
Modify void ask_for_names (string player_1, string player_1) with
void ask_for_names (string& player_1, string& player_1).

And add &s to declaration in line 6.

Read http://www.cplusplus.com/doc/tutorial/functions2/ to know differnce between passing by reference and by value.
Last edited on
It will print out XXX and YYY because you have initialized J1 and J2 to that. You don't actually swap them to the value you want them to hold.
As tfityo said, reference is a way, or a pointer. I would use a pointer really. You point one variable to a new variable that u can use outside of the scope, brilliant stuff who ever came up with that :P
Topic archived. No new replies allowed.