2016-04-12 10 views
0
#include <fstream> 
#include <iostream> 
#include <cstdlib> 
#include <cctype> 

using namespace std; 

void whitespace_replace(ifstream& in_stream, ofstream& out_stream); 
void digit_replace(ifstream& in_stream, ofstream& out_stream); 

int main() 
{ 
    ifstream fin; 
    ofstream fout; 

    cout << "Begin editing files." << endl; 
    fin.open("example.dat"); 

    if (fin.fail()) 
    { 
     cout << "Input file opening failed.\n"; 
     exit(1); 
    } 

    fout.open("example2.dat"); 

    if (fout.fail()) 
    { 
     cout << "Output file opening failed.\n"; 
     exit(1); 
    } 

    whitespace_replace(fin, fout); 
    digit_replace(fin, fout); 
    fin.close(); 
    fout.close(); 
    cout << "End of editing files.\n"; 
    return 0; 
} 

空白をハイフンで置き換える機能。 「#」で数字を交換するストリームC++用の複数の関数

void whitespace_replace(ifstream& in_stream, ofstream& out_stream) 
{ 
    char next; 

    do 
    { 
     in_stream.get(next); 

     if (isdigit(next)) 
      out_stream << '#'; 
     else 
      out_stream << next; 
    } while (next != '.'); 
} 

機能:

void digit_replace(ifstream& in_stream, ofstream& out_stream) 
{ 
    char voip; 
    do 
    { 
     in_stream.get(voip); 

     if (isspace(voip)) 
      out_stream << "-"; 
     else 
      out_stream << "-"; 
    } while (voip != '.'); 
} 

それは私が「#」に私の.datファイル内の数値を変更し、すべて交換することの両方の機能を実行することはできません。空白は ' - 'で囲みます。機能を動作させるためには何が必要ですか?

whitespace_replace(fin, fout); 
digit_replace(fin, fout); 

+2

:あなたに似

1つの方法は、1つの関数呼び出し、この関数では2つの関数のロジックを組み合わせることがあるかもしれませんか?ストリームからデータを読み込んだら、それらはなくなりました。それらを操作するには、それらを変数に保存する必要があります。 – Zereges

+0

あなたの関数の名前は逆になり、現在は 'digit_replace'というラベルの関数はすべての文字を ' - 'で置き換えます。 –

答えて

1

以降の呼び出しは確かにfinfoutに同じストリームの状態が表示されません。

特定の状態の入力から変換するものを単一のパーサ/決定階層に結合する必要があります。第2の機能を呼び出す前に、2番目の関数に渡すときfinfoutの状態は同じではないだろう、とあなたのケースでが戻って最初にストリームを求めている最初の関数から戻った後

0

、あなたが出力に書いたものを取り消すので、あなたがしようとしていることを達成しません。 1つのファイルから読み込み、処理して結果を別のファイルに直接出力する場合は、2つの関数を組み合わせて使用​​する必要があります。そうでなければ、まず入力ファイルからデータを読み込み、それを変数に入れ、個々の関数を呼び出してそのデータを処理し、処理されたデータを出力ファイルに書き出す必要があります。あなたは、これは動作するはずと思いますどのように

char next; 
in_stream.get(next); 
if (isspace(next)) 
    out_stream << "-";//if space replace with '-' 
else if (isdigit(next)) 
    out_stream << "#";//if digit replace with '#'.. 
else 
    out_stream << next; 
関連する問題