how to pass reference of a string

Hi everyone! I'm trying to use "string" library. I wonder that how a "string" is treated, as a normal variable or an array. For example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<iostream>
using namespace std;
#include<string>

void edit(string s);

main(){
       string str;
       getline(cin,str);
       cout<<"before editing, str is: "<<str<<endl;
       edit(str);
       cout<<"after editing, str is: "<<str<<endl;
}

void edit(string s){
     s[1]='A';
}


The result is nothing. It means that I cannot treat string s as an array. But with the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<iostream>
using namespace std;
#include<string>

void edit(string *s);

main(){
       string str;
       getline(cin,str);
       cout<<"before editing, str is: "<<str<<endl;
       edit(&str);
       cout<<"after editing, str is: "<<str<<endl;
}

void edit(string *s){
     s[1]='A';
}


This program is error.

So, how can I pass reference of a string into function? Please help me. Thanks!
Last edited on
You can pass a string into a function as an argument and take a string reference as a parameter in the function.

1
2
3
4
5
6
7
8
// inside main
edit(str);
// ...

// edit function
void edit(string& s) {
    s[1] = 'A';
}


That would work, although s[1] points to the second character in the string because indices start at 0.

A string isn't an array, it is an object of the string class. The reason you can use indexing on a string is because the [] operator is overloaded for the string class (something that you will eventually cover).

What you were doing above is passing a pointer. For it to work the way you had done it your edit function would have to dereference the pointer:

1
2
3
void edit(string* s) {
    (*s)[1] = 'A';
}
Last edited on
Also, DON'T use:

main() or
void main()

Please use:
int main()
Topic archived. No new replies allowed.