C++ 如何从字符中分配std::string*
这可能很琐碎,但我对C++ 如何从字符中分配std::string*,c++,C++,这可能很琐碎,但我对C++还是新手,在这里我会感到困惑 我的方法是: bool load_database_file( const std::string& filename, std::string& contents ) { std::ifstream is (filename, std::ifstream::binary); if (is) { // get length of file: is.seekg (0, is.e
C++
还是新手,在这里我会感到困惑
我的方法是:
bool load_database_file( const std::string& filename, std::string& contents ) {
std::ifstream is (filename, std::ifstream::binary);
if (is) {
// get length of file:
is.seekg (0, is.end);
int length = (int)is.tellg();
is.seekg (0, is.beg);
char * buffer = new char [length];
std::cout << "Reading " << length << " characters... ";
// read data as a block:
is.read (buffer, length);
if (is)
std::cout << "all characters read successfully.";
else
std::cout << "error: only " << is.gcount() << " could be read";
is.close();
// ...buffer contains the entire file...
std::string str(buffer);
contents = str;
delete[] buffer;
}
return true ;
}
bool加载数据库文件(const std::string&filename,std::string&contents){
std::ifstream是(文件名,std::ifstream::binary);
如果(是){
//获取文件的长度:
is.seekg(0,is.end);
int length=(int)是.tellg();
is.seekg(0,is.beg);
字符*缓冲区=新字符[长度];
标准::cout
应该是:
std::string str(buffer, buffer+length);
否则,构造函数如何知道要分配/复制多少字节
顺便说一句,你的代码是不必要的笨拙。为什么不直接读入字符串的缓冲区,而不是使用一个单独的缓冲区,在分配另一个缓冲区之前,你必须分配并释放一个缓冲区来保存数据?你是从哪里得到这个示例的?请注意,在这种情况下,你的长度太短,无法保存以零结尾的字符串,第二,在将字符串分配给std::string
之前,不要零终止字符串。文件使用的是什么编码?@MicroVirus我从这里得到了一个例子:那么我的评论是正确的。David Schwartz的回答回避了这个问题。char*buffer=new char[length];
用这个替换它:std::vector buffer](length);
因为在C++11之前,std::string
中没有连续性的保证?而且,实际上,因为OP应该在循环中读取,以确保他拥有所有字符。你不知道需要多少次读取
调用。循环中的缓冲区是处理这个问题的常规方法。
std::string str(buffer, buffer+length);