模板函数在读取时返回错误的值

Template function returns wrong value while reading

本文关键字:返回 错误 读取 函数      更新时间:2023-10-16

我正在尝试创建一个类,使用模板函数在c++中读取和写入同一个文件,我正在尝试实现读取char或int并返回它的函数read(),当我尝试运行它时,我得到了像-998324343这样的数字,请帮助:)

#include<iostream>
#include<fstream>    
using namespace std;
template <class T>
class myFile
{
ifstream  in;
ofstream out;
public:
myFile(char* fileName)
{
in.open(fileName);
if (!in.is_open())
throw"couldnt open file to reading";
out.open(fileName);
if (!out.is_open())
throw"couldnt open file to writing";
cout << read();
}
T read() {
T x;
in >> x;
return x;
}
};
int main()
{
try {
myFile<int> a("read.txt");
}
catch (char* msg) {
cout << msg << endl;
}
}

您的outin引用同一个文件。所以当这种情况发生时:

in.open(fileName);
if (!in.is_open())
throw"couldnt open file to reading";
out.open(fileName); 

假设fileName作为一个文件存在,out将截断该文件,因此它变为空。后续的in >> x;将失败(因为文件是空的),并且根据编译所依据的C++标准,x将被清零(从C++11开始)或保持未修改(直到C++11)。我假设您正在编译C++11之前的版本,在这种情况下,您看到的是x初始化时使用的不确定值。

不确定您需要out做什么,但您希望它引用不同的文件或以附加模式打开它。

无论out是否正在截断文件,>>操作都可能失败。如果失败,您将获得垃圾数据(或0)。因此,您需要检查该操作的结果。


注意:无论您在哪里使用char*,都应该使用const char*。从字符串文字到char*的转换是不推荐的(如果您在编译时启用了警告,您会看到这种情况)。