2017-02-05 11 views
1
template <class T> 
void savetext(T *a, char const *b) //writes to text file inside .sln however the text file is corrupt 
{ 
    ofstream fout(b, ios::out); 
    for (int i = 0; a[i] != '\0'; i++) 
     fout << a[i] << endl; 
    cout << "Text file successfully written to." << endl; 
} 

template <class T> 
void gettext(T *a, char const *b) //this is where the error occurs: inside the text file it puts the right values along with piles of junk. Why is this? 
{ 

    ifstream fin(b, ios::in); 
    if (fin.is_open()) 
    { 
    cout << "File opened. Now displaying .txt data..." << endl; 
     for (int i = 0; a[i]!= '\0'; i++) 
     { 
      fin >> a[i]; 
     } 
     cout << "Data successfully read." << endl; 
    } 
    else 
    { 
     cout << "File could not be opened." << endl; 
    } 
} 

int main() 
{ 
    const int n1 = 5, n2 = 7, n3 = 6; 
    int a[n1], x, y, z; 
    float b[n2] = {}; 
    char c[n3] = ""; 

    //Begin writing files to text files which I name herein. 
    cout << "Writing data to text 3 text files." << endl; 
    savetext(a, "integer.txt"); 
    savetext(b, "float.txt"); 
    savetext(c, "string.txt"); 
    cout << endl; 

    //Retrieve the text in the files and display them on console to prove that they work. 
    cout << "Now reading files, bitch!" << endl; 
    gettext(a, "integer.txt"); 
    gettext(b, "float.txt"); 
    gettext(c, "string.txt"); 
    cout << endl; 

    return 0; 

system("PAUSE"); 
} 

こんにちは、おはよう。私は現在、3つの別々のテキストファイルにデータ(整数、浮動小数点数、文字)を書いているC++プログラムを持っています。しかし、テキストファイルにデータを書き込むとき、データはテキストファイルの中にありますが、判読不能なテキストと大量の数字と大きい負の数値 - 決して入力しなかったデータです。テキストファイルに書き込まれたデータが部分的に破損し、取り戻せません。

この結果、テキストファイルから情報を取得できず、テキストファイルの情報を表示できません。どうすれば問題を解決できますか?ありがとうございました。

+0

スタティック・アレイではなく、std :: vectorを使用していますか?あなたのプログラムがファイルから可変バイト数を読み取る場合、動的に割り当てられたコンテナ(std :: vectorなど)は、固定バイト数しか保持できない静的配列よりも優れています。ファイルサイズは使用可能なメモリよりも大きくなる可能性があるので、ファイルをハードディスクから読み取って処理することをお勧めします。この方法では、ファイルからメモリにすべてのデータを同時に保存することはありません。また、クロスプラットフォームの場合は、エンディアンとUnicodeエンコーディングについて考える必要があります。 –

答えて

0

最初の問題は、ファイルに初期化されていないデータを書き込むことです。

+0

Hm。私は 'main()'で初期化したという印象を受けていますか? '' int a [n1]、x、y、z; 'は初期化ではないのですか?そうでない場合は、どこで何をすべきですか?ありがとうリッチ。 – ZoeVillanova

+0

文字列は "空"です。つまり、最初の文字は\ 0です。私は思い出しませんが、bが初期化された値を持つためには中括弧の値が必要だと思います。ただし、a、x、y、zはすべて初期化されていません。 – Rich

+0

ファイルストリームの代わりにcoutを使用するように関数を変更し、取得した内容を確認します。 – Rich

関連する問題