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

2

Recently I made a question, why istreambuf_iterator does not work in android NDK , as I had no answer I decided to find out myself, I created a project in Visual Studio 2017, simple thing, just to read a file in binary mode and show the result in the console, here is my code: / p>

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 output:

Andnowc_str();

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

    
asked by anonymous 02.04.2018 / 16:12

1 answer

3

Simple, the string of C is delimited by the null character 'string' . , so if it finds it, it is considered that the string is gone. Other than type c_ str() that has its size determined and does not use a delimiter character. Since what you are reading is not text but binary content, it is very easy to find a null in content, and this happens.

As there is no reason to use string is not a problem. In fact neither %code% should be used for something that is not text. The error is conceptual.

    
02.04.2018 / 16:20