2016-04-28 45 views
-4

我正在阅读以下文本文件逐字替换单词“@ name @”和“@ festival @”。我的程序完美适用于@ name @,但只改变了第一个@ festival @,但不是第二个。我不知道为什么。为什么我可以在文本文件中替换一个单词而不是另一个单词?

李四

客房213-A

通用旧建筑

信息学院科技

编程州立大学

纽约NY 12345-0987

美国

要:@名@

主题:节日的问候:@节@

亲爱的@名@,

一个非常@节@你和你的家人!

你的真诚,

约翰

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 == "@[email protected]") { 
       word = name; 
      } 
      if (word == "@[email protected]") { 
       word = "THISISATEST!!!!!!!!!!!!!!"; 
      } 
      word = word + x; 
      x = file.get(); 
     } 

     out << word + " "; 
     word.clear(); 
    } 
} 
+0

当您逐步完成代码时,调试器会显示什么内容? –

回答

0

首先,看Why is iostream::eof inside a loop condition considered wrong?

这不是一个完美的解决方案......但是更好的改善您的原代码。 (我会让你想到更高效的解决方案):

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 = "@[email protected]", festivalHolder = "@[email protected]"; 
    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'; 
    } 
} 
+0

谢谢,解决了这个问题 – thefreeman

1

问题是内部条件的同时,如果存在' ' @节@以后,会不会是真的。下面的代码是所有的正确

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 == "@[email protected]") { 
      word = name; 
     } 
     if (word == "@[email protected]") { 
      word = "THISISATEST!!!!!!!!!!!!!!"; 
     } 
     word = word + x; 
     x = file.get(); 
    } 
    if (word == "@[email protected]") { 
      word = name; 
    } 
    if (word == "@[email protected]") { 
     word = "THISISATEST!!!!!!!!!!!!!!"; 
    } 

    out << word + " "; 
    word.clear(); 
    } 
} 
+0

我看到你在说什么,我试着做出你的改变并且工作。不幸的是,我需要它为x个字符串工作,但是,至少我知道现在有什么错误 – thefreeman

相关问题