2016-04-28 33 views
-4

私は次のテキストファイルの単語を読み、 "@ name @"と "@ festival @"という単語を置き換えています。私のプログラムは@ name @のためには完全に動作しますが、最初の@festival @だけを変更しますが、2番目の@は変更しません。なぜ私は考えていない。テキストファイル内の1つの単語を置き換えることはできますが、別の単語を置き換えることはできますか?

ジョン・ドウ

ルーム213-

ジェネリック旧ビル

情報技術科

プログラミング州立大学

ニューヨークNY 12345から0987

USA

へ:季節の挨拶:名@

件名@名@ @

親愛なる、

A非常に祭り@ @ @ @祭りあなたとあなたの家族に!

あなたの誠実、

ジョン

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

問題は、@祭り@の後' 'を存在する場合、それは真実でないことを、内側のwhile条件です。以下のコードのすべての

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

関連する問題