2016-11-04 5 views
1

ここではthis questionに出くわしました。私はstackoverflowを初めて使ったので、答えは得られません。それに答えた人はcincoutの代わりに< < >>を置き換えるのが正しいと思われます。しかし、問題は、すべてのセミコロンが新しい出力ファイルに表示されないということです。I/Oストリーム文字列操作(正しいCin/cout演算子<</>>)

私はstd::getline(input, command, ';')ながら、すべてのセミコロンを消去しますが、最後にelse文を戻すことを聞きしたいはずが、私はそれを実行したときに、それが交換されていないことを知っています。私が ';'を省略すると、 getlineステートメントのうち、出力ファイルのすべてが壊れてしまいます。

セミコロンが表示されるようにするにはどうすればよいですか?

void print(ifstream& input,ofstream& output) 
{ 
    bool first = true; 
    std::string command; 
    while(std::getline(input, command, ';')) 
    { // loop until no more input to read or input fails to be read 
     if (command.find("cin")!= std::string::npos) 
     { // found cin somewhere in command. This is too crude to work. See below 
      size_t pos = command.find("<<"); // look for the first << 
      while (pos != std::string::npos) 
      { // keep replacing and looking until end of string 
       command.replace(pos, 2, ">>"); // replace with >> 
       pos = command.find("<<", pos); // look for another 
      } 
     } 
     else if (command.find("cout")!= std::string::npos) 
     { // same as above, but other way around 
      size_t pos = command.find(">>"); 
      while (pos != std::string::npos) 
      { 
       command.replace(pos, 2, "<<"); 
       pos = command.find(">>", pos); 
      } 
     } 
     if (! first) 
     { 
      output << command; // write string to output 
     } 
     else 
     { 
      first = false; 
      output << ';' << command; // write string to output 
     } 
    } 
} 
+0

'std :: getline'関数はflleの内容を変更しません。 –

+0

問題のあるコードで質問を編集してください。 –

+0

お詫び申し上げます。編集されました。 – Deegeeek

答えて

0

問題はここにある:最初の繰り返しで

 if (! first) 
     { 
      output << command; // write string to output 
     } 
     else 
     { 
      first = false; 
      output << ';' << command; // write string to output 
     } 

elseブランチが実行されますと、セミコロンが印刷されます。

以降の反復では、ではないifブランチが実行され、はセミコロンを出力しません。

修正は簡単です:output <<で始まる2行を入れ替えてください。

+0

ありがとうございます。それは今働いているようだ。しかし、テスト中のtxtファイルの先頭にセミコロンが現れます。 getlineで取り消されたセミコロンはすべて復帰しましたが、新しいものがファイルの最初の文字として表示されます。 – Deegeeek

+0

実際に修正しました。 'if(!flag)'ステートメントの中で、 '&&!(line.find("# ")!= string :: npos)を追加しました)' ' – Deegeeek

関連する問題