Overwrite data in a string

I been experimenting to modify data in a string with string.replace and string.erase but now I need to overwrite say 20bytes with say 10byte word but leave the extra as whitespace. How can I do this?
what do you mean with "extra"?
because when I use replace, those 20bytes of data in my string come down to 10bytes. I need to clear the previous data in those 20bytes and then put for example 10bytes and leave the rest (other 10bytes) with whitespace. I tried to add the white space to my word by word += ' ' in a for loop but then write my string to binary file. When I read the binary file again in binary mode, I get my data that wasnt modified as it is, while the data that was added as white space is printed out as garbage and I need to remove this.

What I am trying to do is this: read binary file to string, modify string and write to binary file again.
Last edited on
I'd try this solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int main(int argc, char *argv)
{
    string A="the 20byte text";
    string B="the 10byte text";
    
    string temp;    //Temporary string with the value of B as its content
    temp=B;

    int test=A.length()-B.length();    //The number of whitespaces you have to add

    for(int i=0;i<test;i++)
    {
        temp.append(" ");    //This function adds a whitespace to temp
    }

    B=temp;    //At last, B must get the same as temp. Now, B is the value of B plus the whitespaces to get to the size of A

    return 0;
}


I hope, it'll help you.
The Data is updated perfectly with your method, in fact when I read the user profiles back from the binary file, they are input to a struct made of name, age, score, and 'lastword' (hangman game) and these are view perfectly which shows that the whitespace is added well and things match. Now the only thing is that after the profile that was updated there are a bunch of very strange characters, it is like as if the binary to ascii conversion is converting some of the white space to very strange characters. What do you thing this might be and how can I fix it?

Last edited on
Okay, I found the issue :) .. before I was reading the binary file by inputting each profile to a struct I was initializing my struct with:

PlayerInfo sPlayer = {0};

when I commented it out, no more strange character printed out on my screen but only my wanted details. Can anyone explain what happened pls?
May you please show me the source code? Then I'd be more able to judge your problem =)
Topic archived. No new replies allowed.