Reading from a .txt, replacing word, then overwritng .txt

My goal is to open a .txt file and replace words in it then overwrite it. My goal is half way done. It couts it perfectly, but I am having a hard time overwriting the whole text file exactly how it couts it. I want the text to be exactly how it is displayed. In this example, I want to replace "ABC" with "DEF".

Text file "A.txt":
1 2 ABC 4 5
6 ABC 8

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
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
    string Y;
    fstream IN("A.txt", ios::in | ios::out);
    while(getline(IN,Y))
    {
        for(int X=0; X<Y.length(); X++)
        {
            if(Y.find("ABC")==X)
            {
                IN<<Y.replace(X, 3, "DEF");
            }
        }
        cout<<Y<<'\n';
    }
    IN.close();
    return 0;
    if(!IN)
    {
        cout<<"Failed to open file.\n";
    }
}

Any hints or tips? I appreciate the time and effort in helping me.
Last edited on
1
2
3
4
5
6
7
for(int X=0; X<Y.length(); X++)
{
    if(Y.find("ABC")==X)
    {
         IN<<Y.replace(X, 3, "DEF");
    }
}
This is so-called for-if antipattern.
You do not need for loop here. Nor you need to output line right after replacing: you will output it again later.

replace it with:
1
2
3
4
std::string::size_type n;
while((n = Y.find("ABC")) != std::string::npos) { //In case if there more than one ABC in line
    Y.replace(n, 3, "DEF");
}
Last edited on
save your output in a temporary buffer
i would just close the file and open it again to write on it.
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include "stdafx.h"
#include<iostream>
#include<string>
#include<fstream>
#include<sstream>

using namespace std;
int main()
{
	string Y;
	stringstream output;	
	ifstream IN("A.txt");

	if (!IN)
	{
		cout << "Failed to open file.\n";
	}
	else
	{
		while (!IN.eof())
		{
			getline(IN, Y);

			for (int X = 0; X < Y.length(); X++)
			{
				if (Y.find("ABC") == X)
				{
					Y.replace(X, 3, "DEF");
				}
			}
			
			output << Y << "\n";
						
		}

		cout << output.str() << '\n';
		
		IN.close();
	}	

	ofstream out("B.txt");
	out.write(output.str().c_str(), output.str().size());
	out.close();

	int x;
	cin >> x;

	return 0;

}
Thank you both they worked great and I have used both of your suggestions together. So just for future reference, the way that I was doing it was not possible?
Topic archived. No new replies allowed.