1

これは、私が数分前に尋ねたばかりの質問のリメイクです。基本的には、改行数より1つ少ない改行を表示したいです。したがって、改行が 3 行続いている場合、改行は 2 行にする必要があります。これを行う方法はありますか?

while( infile.get( ch ) ) 
{
  switch( ch )
  {
    case '\n':
        outfile << "<br />";
        break;
    case '\t':
        outfile << tab;
        break;
    case '&':
        outfile << "&amp;";
        break;
    case '<':
            outfile << "&lt;";
        break;
    case '>':
            outfile << "&gt;";
        break;
    case '"':
            outfile << "&quot;";
        break;
    default:
        outfile << ch;
        break;
 }  

if( ch == '\n' )
 {
   inputLines++;
 }

}

サンプル出力は次のようになります: https://gist.github.com/anonymous/b5a647913f83f796914c

4

2 に答える 2

0

この問題を解決するには、「同じものが複数ある」ことを検出する必要があります。これは、一種のステートマシンを構築することを意味します。

あなたがしていることだけに対処するための単純なバージョンは、「ピークバッファ」を持つことです。

#include <fstream>
#include <iostream>

using namespace std;


int buffer = 0;

int peek(ifstream &infile)
{
   if (buffer) return buffer;
   char ch;
   if (!infile.get( ch ))
       buffer = -1;
   else
       buffer = ch;
   return buffer;
}

int get(ifstream &infile)
{
   int ch = peek(infile);
   buffer = 0;
   cout << "ch = " << ch << endl;
   return ch;
}

int main(int argc, char **argv)
{
    ifstream infile(argv[1]);
    ofstream outfile(argv[2]);

    int ch;
    while( (ch = get(infile)) != -1 ) 
    {
        int count = 0;
        switch( ch )
        {
        case '\n':
            while (peek(infile) == '\n')
            {
                count ++;
                get(infile);
            }
            count--;  // One less. 
            if (count <= 0) count = 1;    // Assuming we want one output if there is only one. 
            for(int i = 0; i < count; i++)
            {
                outfile << "<br />";
            }
            break;
        default:
            outfile << (char)ch;
            break;
        }
    }
}

これを行うための他の賢い方法があると確信しています。

于 2013-07-10T13:58:29.527 に答える
0

これはあなたのために働くかもしれません。基本的に、検出された最初の改行をスキップします。3 つの改行入力がある場合は、2 つの改行があります。改行が 1 つしかない場合は、改行文字 (改行ではない) が表示されることに注意してください。

bool first_nl = true;
while( infile.get( ch ) ) 
{
    switch( ch )
    {
        case '\n':
            if ( first_nl ) {
                outfile << "\n";
                first_nl = false;

            } else {
                outfile << "<br />\n";
            }
            break;

        case '\t':
            outfile << tab;
            break;

        case '&':
            outfile << "&amp;";
            break;

        case '<':
            outfile << "&lt;";
            break;

        case '>':
            outfile << "&gt;";
            break;

        case '"':
            outfile << "&quot;";
            break;

        default:
            outfile << ch;
            break;
    }

    if( ch == '\n' )
    {
        inputLines++;

    } else {
        first_nl = true;
    }
}

これを使用すると、次の文字を「のぞき見」する必要がなくなります。

于 2013-07-10T15:04:16.170 に答える