为什么我可以替换文本文件中的一个单词,而不能替换另一个单词
Why can I replace one word in a text file but not another?
我正在逐字逐句地阅读下面的文本文件,替换单词"@name@"answers"@festival@"。我的程序非常适用于@name@,但只更改了第一个"节日",而没有更改第二个。我不知道为什么。
John Doe
房间213-A
通用老建筑
信息技术学院
编程州立大学
纽约州纽约市12345-0987
美国
收件人:@name@
主题:节日问候:@festival@
尊敬的@name@,
祝你和你的家人节日快乐!
您的真诚,
约翰·
void Main::readFile()
{
while (v.size() != 0) {
string name;
name = v.at(v.size()-1);
v.pop_back();
std::ofstream out(name + ".txt");
ifstream file;
file.open("letter.txt");
string word;
string comma;
char x;
word.clear();
while (!file.eof())
{
x = file.get();
while (x != ' ' && x != std::ifstream::traits_type::eof())
{
if (word == "@name@") {
word = name;
}
if (word == "@festival@") {
word = "THISISATEST!!!!!!!!!!!!!!";
}
word = word + x;
x = file.get();
}
out << word + " ";
word.clear();
}
}
问题是内部while条件,如果在@festival@之后存在' '
,则问题将不成立。以下代码是正确的
void Main::readFile()
{
while (v.size() != 0) {
string name;
name = v.at(v.size()-1);
v.pop_back();
std::ofstream out(name + ".txt");
ifstream file;
file.open("letter.txt");
string word;
string comma;
char x;
word.clear();
while (!file.eof())
{
x = file.get();
while (x != ' ' && x != std::ifstream::traits_type::eof())
{
if (word == "@name@") {
word = name;
}
if (word == "@festival@") {
word = "THISISATEST!!!!!!!!!!!!!!";
}
word = word + x;
x = file.get();
}
if (word == "@name@") {
word = name;
}
if (word == "@festival@") {
word = "THISISATEST!!!!!!!!!!!!!!";
}
out << word + " ";
word.clear();
}
}
首先,请参阅为什么循环条件中的iostream::eof被认为是错误的?
这不是一个优雅的解决方案。。。但这是对原始代码的更好改进。(我让你想想更有效的解决方案):
void Main::readFile()
{
while (v.size() != 0) {
string name;
name = v.at(v.size()-1);
v.pop_back();
std::ofstream out(name + ".txt");
ifstream file;
file.open("letter.txt");
string festival = "THISISATEST!!!";
string line, nameHolder = "@name@", festivalHolder = "@festival@";
while (std::getline(file, line))
{
std::size_t n_i = line.find(nameHolder);
if(n_i != std::string::npos)
line.replace(n_i, nameHolder.size(), name);
std::size_t f_i = line.find(festivalHolder);
if(f_i != std::string::npos)
line.replace(f_i, festivalHolder.size(), festival);
out << line << 'n';
}
}
相关文章:
- 替换字符串中的单词,但忽略引号中的单词
- 替换字符串位置 X 中的单词C++
- C++正则表达式替换整个单词
- 从文件中查找单词并替换到其他文件中
- 将字符串中的单个单词替换为另一个单词
- 创建程序以从给定的.txt文件中查找文本,替换并计算单词
- 给定一个字符串,只要您看到单词"ant"替换到字符串中,单词就会"termite"
- 尝试修复一个字符串函数,该函数采用字符串并通过替换一些单词来更改它
- 如何用新单词替换未知数量的相同字符
- 如何将文件复制到另一个文件中,但是用用户输入的单词替换单词
- C 查找并替换整个单词
- 使用C 替换文本文件中的单词
- 如何在任何位置阅读和替换C++单词
- 通过文本文件逐字通知并替换某些单词
- C++将<单词 A>替换为<单词包含 A>
- 将任何以 n F 开头或以 f 开头的单词替换为 *
- 为什么我可以替换文本文件中的一个单词,而不能替换另一个单词
- 用不同字符替换单词的代码
- 将文本文件中的特定单词:C++替换为预定义值
- 将文件中的特定单词替换为另一个单词