【问题标题】:How can I assign a std::string from a char * [duplicate]如何从 char * [重复] 分配 std::string
【发布时间】:2014-08-28 07:01:27
【问题描述】:

这可能是微不足道的,但我是 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 ;  
}

我想读取一个文件并将其内容分配给contents,以便调用函数可以读取它。

我的问题是这个函数运行后,我看到只有buffer的第一个字符被复制到contents

如何将bufferchar *)的全部内容复制/转换为contentsstd::string)。

【问题讨论】:

  • 您是否从here 获得示例?请注意,在这种情况下,您的长度太短而无法容纳以零结尾的字符串,其次您在将字符串分配给 std::string 之前不要以零结尾。
  • 文件使用什么编码?
  • @MicroVirus 我从这里得到了例子:cplusplus.com/reference/istream/istream/read
  • 那么我的话成立。 David Schwartz 的回答绕过了这个问题。
  • char * buffer = new char [length]; 替换为:std::vector&lt;char&gt; buffer(length);

标签: c++


【解决方案1】:
    std::string str(buffer);

应该是:

    std::string str(buffer, buffer+length);

否则,构造函数怎么知道要分配/复制多少字节?

顺便说一句,您的代码非常笨拙。为什么不直接读入字符串的缓冲区,而不是使用一个单独的缓冲区,在分配另一个缓冲区之前,您必须分配和释放只是为了保存数据?

【讨论】:

  • 因为在 C++11 之前没有保证std::string 的连续性?而且,实际上,因为 OP 应该 循环读取,以确保他拥有所有字符。您不知道需要多少 read 调用。循环内的缓冲区是处理它的常规方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-10
  • 2012-10-31
  • 2015-11-07
  • 1970-01-01
  • 1970-01-01
  • 2012-01-06
相关资源
最近更新 更多