读取文本文件并输出字符串
Read textfile and output string
下面我有一个代码,它读取一个文本文件,并且只有在其中包含单词"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;
}
相关文章:
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何从void函数输出字符串
- 输出字符串数组
- 如何输出字符串第二个单词的第一个字母?
- 多线程环境中的输出字符串流出现问题
- 输出字符串到cmd显示的右显示,但未被认为是命令
- 读取文本文件并输出字符串
- 输出字符串使用 C++ 覆盖 Linux 终端上的最后一个字符串
- 如何在C++中输出字符串的向量
- 无法从类模板输出字符串
- FWRITE 输出字符串不正确
- Qt单元测试输出字符串长度截止
- 无法显示输出字符串
- 如果条目大于90,则输出字符串的布尔函数
- C++不带 'n' 或 endl 的输出字符串将在字符串末尾输出'#'
- 在C++中输出字符串和 strncpy 时遇到问题
- 获取c#输出字符串参数值为c++ BSTR*
- C++初学者,开关不输出字符串的第一个字符
- 输出字符串/字符错误(c++)
- Getline()省略输出字符串的第一个字母