Help with code that modifies string

Hy guys,

I'm havin a problem with this coe bellow.
It's supposed to transform text on the wall to text user wants e.g. from "efgh afao gagsw" --> "###h ###o ####w".
My code keep on chrashing when it gets to function Vandal :/
I know it would be better to use chars and then pointers :D

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

using namespace std;

void Vandal(string T1, string T2)
{   int n=T1.size();

    for (int i(1);i<=n;i++)
    {
        if(T1[i]!=T2[i])
            T1[i]='#';
    }
    cout<<T1;

}

int main()
{   string napis, cilj;
    int n;

    cout<<"What's written on the wall...\n";
    getline(cin, napis);
    cout<<"What would you like to be on the wall...\n";
    getline (cin,cilj);

    Vandal(napis, cilj);

    return 0;
}
variable i needs to be initialized with 0 and cycle goes till i<n ...
from what you have written, you want spaces to be left as spaces, so you need to check if character == space
Last edited on
Done that...It's not chrashing now ty.
It wasnt working at all so I didn't bother with spaces so far :D
But yeah they should be left as spaces.
But no I have a problem that his code only checks paralel characters, like first in T1 with first in T2, so there is hardly any chance to get the output you would want. So how should I do that It would keep checking for one particulat charaster and went throught whole loop.
a nested cycle for is good...

1
2
3
4
5
6
7
for()   //  goes through T1
{
       for()   // goes through T2
       {
              // check characters
       }
}


or use some string functions
Last edited on
This line:

for (int i(1);i<=n;i++)
Should be:

for (int i(1); i < n; i++)

Also if you are trying to modify the strings so that changes remain after control gets back to main, you should be passing the string variables by reference rather than by value

http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/
Last edited on
Great, thank you guys.

@rich1: I didn't remembered that, will try it asap

@Smac89: Okay, I'll correct this line + I know that, thats why I've put cout inside the function.

Thank you again for your help.
Topic archived. No new replies allowed.