模板函数在读取时返回错误的值
Template function returns wrong value while reading
我正在尝试创建一个类,使用模板函数在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;
}
}
您的out
和in
引用同一个文件。所以当这种情况发生时:
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*
的转换是不推荐的(如果您在编译时启用了警告,您会看到这种情况)。
相关文章:
- (C++)分析树以计算返回错误值的简单算术表达式
- glad 导致 glfwSwapBuffers 返回错误消息
- 我的模板类方法返回错误类型?
- 共享内存:MapViewOfFile 返回错误 5
- 使用 std::forward_list 返回错误的队列实现
- FFMPEG:sws_scale返回错误:切片参数 0, 2160 无效
- __int64 CString 返回错误的值 - C++ MFC
- C++ OpenGL 中,绘制形状返回错误
- Python os.system() 返回错误值
- 函数从指针 c++ 中获取错误的值并返回错误的答案
- LibClang clang_getArgType() 返回错误的类型
- 除法函数返回错误的值
- 当命令失败时,gzip 会在 C++ 中返回错误代码吗?
- 矩阵逆变器返回错误的反转
- openCL-创建子缓冲区返回错误代码13
- Qt SQL LIKE语句返回错误
- GetLastError()从FtpPutFile()返回错误6
- PfCreateInterface返回错误120(未实现)
- 为什么 Pa_GetStreamTime() 返回错误?
- G++ 在尝试使用 G++ 使用 openCV 进行编译后返回错误