ifstream 对象的 .read() 问题 *char
ifstream Object's .read() Problems of *char
我的代码:
ifstream Reader ("commands.txt");
if(Reader.fail())
{
error("File "commands.txt" could not be found or opened.n");
}
Reader.seekg(0, Reader.end);
int FSize = Reader.tellg();
if(FSize == 0)
{
cout << "File "commands.txt" is empty.n";
return 0;
}
char * ContentsHold = {};
Reader.read(ContentsHold, FSize);
Reader.close();
string Contents(ContentsHold);
这个想法是,在最后,Contents应该是一个c++字符串,它包含commands.txt中的所有内容。我得到了错误"basic_string::_S_construct null not valid"。我不知道出了什么问题。帮助
这里有什么,
char* ContentsHold = {};
声明一个指向用null常量初始化的字符的指针。这不是指向数组第一个元素的指针,您必须使用new[]
语法:
char* ContentsHold = new char[FSize];
这将创建一个数组,并且ContentsHold
将指向它的第一个元素。更好的方法是使用std::string
并公开其第一个元素的地址:
std::string ContentsHold(FSize);
Reader.read(&ContentsHold[0], FSize);
这样你就不用担心删除新的内存了。
相关文章:
- 构造函数 (C++) 中的 char 指针参数存在问题
- 没有'str'成员在 GCC 和 Clang 'std::basic_ostream<char>',但 MSVC 没有问题
- 通过指针使用C++还原char数组时出现问题
- "char(a)" C++的问题
- 愚蠢的问题:strcat和char指针
- 语法问题:"char [5] const &"是什么意思?
- 如何将char数组声明为函数参数?或告诉我此代码中还有其他问题?
- Char 数组的问题,如何正确构造和显示它们
- 使用C ,将转换为char的问题始终具有3位数字
- 将 char* 推送到矢量时出现问题,但在每次迭代后,它会将指向相同值缓冲区的指针添加到矢量中
- char,const char*阵列问题,用于mqtt client.publish
- 以C++语言打印 CHAR 数组时出现问题
- 将 API 函数参数从 'char *' 更改为"const char *"有哪些潜在问题?
- 接受类型char的输入的问题
- 有人能解释一下getline和char的问题吗
- Windows 10中的Char*的内存分配问题
- 将 char * 与字符串文本进行比较时出现问题
- 将wchar_t*转换为char*时出现问题
- FLTK和串联char的问题
- ifstream 对象的 .read() 问题 *char