读取文本文件并输出字符串

Read textfile and output string

本文关键字:输出 字符串 文件 取文本 读取      更新时间:2023-10-16

下面我有一个代码,它读取一个文本文件,并且只有在其中包含单词"unique_chars"的情况下才向另一文本文件写入一行。我在这行上还有其他垃圾,例如。"column"我如何让它用"wall"之类的其他东西来代替短语"column"

所以我的线路就像<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;
}

如果您希望替换所有出现的字符串,您可以实现自己的replaceAll函数。

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

要进行替换,您可以使用std::string的方法"replace",它需要一个开始和结束位置以及字符串/令牌来代替您要删除的内容,如:

(您还忘记在代码中包含字符串标题)

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