C++ Std::string.c_str() always returning NULL

Asked

Viewed 105 times

2

I recently asked a question, because istreambuf_iterator does not work on android NDK, as I had no answer I decided to investigate myself, I created a project in Visual Studio 2017, simple thing, only to read a file in binary mode and show the result in the console, here is my code:

Main.cpp

#include <iostream>
#include <string>
#include "Cart.h"

int main(int argc, char *argv[])
{

    std::string fileName;

    std::cin >> fileName;

    Cart cart(fileName.c_str());
    cart.loadContent();

    std::system("PAUSE");
    return EXIT_SUCCESS;
}

Cart. h

#pragma once

class Cart {

public:

    Cart(const char *fileName);
    ~Cart();

    virtual void loadContent();

private:

    const char *m_FileName;
};

Cart.cpp

#include <fstream>
#include <string>
#include <iostream>
#include "Cart.h"

Cart::Cart(const char *fileName)
{
    this->m_FileName = fileName;
}

Cart::~Cart()
{

}

void Cart::loadContent()
{

    std::fstream cartFile(m_FileName, std::ios::in | std::ios::binary);

    if (!cartFile.bad()) {

        std::string content((std::istreambuf_iterator<char>(cartFile)), (std::istreambuf_iterator<char>()));
        std::cout << "STD::String: " << content << std::endl;
        std::cout << "Const Char*: " << content.c_str() << std::endl;
    }

    cartFile.close();
}

And I have the following exit:

Saída de std::string

And now c_str();

Saída de c_str()

Well, what could you be doing c_str() not work with istreambuf_iterator<char>(cartFile)?

1 answer

3


Simple, the string of C is bounded by the null character '\0', then if you meet him, it is considered that the string ended. Different from the type string which has its specified size and does not use a delimiting character. Since what you are reading is not text but binary content, it is very easy to find a null in the content, and this occurs.

Since there’s no reason to use the c_ str() is not a problem. Actually neither string should be used for something that is not text. The error is conceptual.

  • a problem solved, now the question is, how to turn that into an unsigned char? tried Std::string content((Std::istreambuf_iterator<char>(cartFile)), (Std::istreambuf_iterator<char>()); const int i = content.length() + 1; unsigned char str[i];

  • But vs accuses not possible

  • That’s another problem, I’d need to better understand it in another question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.