Strings

What am I missing here to correctly modifiy string a?

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
#include <iostream>
#include <string>

using namespace std;

void change(string a)
{
    string b;

    for(int i = 0; i < a.size(); i++)
    {
        if(a[i] == ' ')
        {
            b += "%20";
        }
        else{
            b+= a[i];
        }
    }

    a = b;
}


int main()
{
    string a = "Mr John Smith";
    change(a);
    cout << a;
}
Last edited on
Pass the string by reference.
void change(string& a)
note that f(x) = " function "

How are you planning to modify your char array/string? Another thing I see, is the formal parameter:
1
2
3
4
5
6
void changeStr(string a) 
// string a, in the f(x) definition is called a formal 
//parameter (thats when its outside of the f(x) main) and when you call the
//function inside the function main you apply the actual parameter. 
//like so
changeStr( originalStr); //or ( a ) if were using your code. 

Another thing, if you want to use the changes to the string outside of the scope of the f(x), you need to change the type of function to string.

For example:
1
2
3
4
5
6
7
8
 string changeStr( string changedStr){

//How you want to change the string.

//At the end of the f(x) return the changed string.

return changedStr;
}


One last pointer, the more you use pseudo code. The easier it's to understand the value of the variable in the program.
newStr = "Hello World"
diffStr = "Good Bye World"

Last edited on
What the other guy did would require a pointer and you can do this. You wouldn't need to change the type of function from void to string but you still need to change the formal parameter so that its different from the actual parameter. Not a bad way to go either.
Topic archived. No new replies allowed.