簡體   English   中英

寫入文本文件的數據部分損壞且無法恢復

[英]data written to text file is partially corrupt and irretrievable

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個單獨的文本文件。 但是,當它將數據寫入文本文件時會發生兩件事:數據在文本文件中,但是一堆難以理解的翼文本和大數字和大的負數 - 我從未輸入過的數據。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM