2017-02-05 20 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"); 
} 

您好,晚上好。我有一個C++程序,目前正在將數據(整數,浮點數和字符)寫入3個單獨的文本文件。然而,當它將數據寫入文本文件時,會發生兩件事情:數據在文本文件中,但是也有一些不可理解的動態文本和大量數字以及大量負數 - 我從未輸入數據。寫入文本文件的數據部分損壞且無法挽回

因此,我無法從文本文件中檢索信息,也無法顯示文本文件的信息。我該如何解決這個問題?謝謝。

+0

正在使用std :: vector而不是靜態數組ok嗎?如果程序從文件中讀取可變數量的字節,動態分配的容器(如std :: vector)比只能保持固定數量字節的靜態數組要好。由於文件大小可能比可用內存大,因此從硬盤讀取文件時處理文件是個不錯的主意。這樣可以避免將文件中的所有數據同時存儲到內存中。如果您跨平臺,還必須考慮排序和Unicode編碼。 –

回答

0

您的第一個問題是您正在向您的文件寫入未初始化的數據。

+0

嗯。我的印象是我在'main()'中初​​始化了它們,我沒有嗎? 'char c [n3] =「」;','float b [n2] = {};'和int a [n1],x,y,z;'是不是初始化?如果他們不是,我應該在哪裏以及如何做?謝謝Rich。 – ZoeVillanova

+0

字符串是「空的」,這意味着第一個字符是\ 0。我不記得了,但我認爲你需要一個花括號來讓b有一個初始化值。但是,a,x,y和z都未初始化。 – Rich

+0

將您的功能更改爲使用cout而不是文件流並查看所得到的結果。 – Rich