2017-02-05 32 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