soniccool
soniccool

Reputation: 6058

Read textfile and output string

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;
}

Upvotes: 1

Views: 199

Answers (2)

Borgleader
Borgleader

Reputation: 15916

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;
}

Upvotes: 1

Rapptz
Rapptz

Reputation: 21317

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();
    }
}

Upvotes: 2

Related Questions