1

Below i have a code that reads a text file and only writes a line to another textfile if it has the word "unique_chars" in it. I also have other garbage on that line such as for example. "column" How can i make it replace the phrase "column" with something else such as "wall"?

So my line would be like <column name="unique_chars">x22k7c67</column>

#include <iostream>
#include <fstream>

using namespace std;

int main()
{

    ifstream  stream1("source2.txt");
    string line ;
    ofstream stream2("target2.txt");

        while( std::getline( stream1, line ) )
        {
            if(line.find("unique_chars") != string::npos){
             stream2 << line << endl;
                cout << line << endl;
            }

        }


    stream1.close();
    stream2.close();    

    return 0;
}
2
  • You forgot to include <string> Commented Sep 7, 2012 at 22:34
  • 1
    Take a look at string's replace function. Commented Sep 7, 2012 at 22:37

2 Answers 2

2

If you wish to replace all occurrences of the string you could implement your own replaceAll function.

void replaceAll(std::string& str, const std::string& from, const std::string& to) {
    if(from.empty())
        return;
    size_t pos = 0;
    while((pos = str.find(from, pos)) != std::string::npos) {
        str.replace(pos, from.length(), to);
        pos += to.length();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

To do the substitution you can use std::string's method "replace", it requires a start and end position and the string/token that will take the place of what you're removing like so:

(Also you forgot include the string header in your code)

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    ifstream  stream1("source2.txt");
    string line;
    ofstream stream2("target2.txt");

    while(getline( stream1, line ))
    {
        if(line.find("unique_chars") != string::npos)
        {
            string token("column ");
            string newToken("wall ");
            int pos = line.find(token);

            line = line.replace(pos, pos + token.length(), newToken);
            stream2 << line << endl;
            cout << line << endl;
        }
    }

    stream1.close();
    stream2.close();    

    system("pause");
    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.