How can I read from memory just like from a file using wistream?

倖福魔咒の 提交于 2019-12-04 16:41:59
ybungalobill

I assume that your data is already converted into the desired encoding (see @detunized answer).

Using my answer to your previous question the conversion is straight forward:

namespace io = boost::iostreams;

io::filtering_wistream in;
in.push(warray_source(array, arraySize));

If you insist on not using boost then the conversion goes as follows (still straight forward):

class membuf : public wstreambuf // <- !!!HERE!!!
{
    public:
        membuf(wchar_t* p, size_t n) { // <- !!!HERE!!!
        setg(p, p, p + n);
    }
};

int main()
{
    wchar_t buffer[] = L"Hello World!\nThis is next line\nThe last line";  
    membuf mb(buffer, sizeof(buffer)/sizeof(buffer[0]));

    wistream istr(&mb);
    wstring line;
    while(getline(istr, line))
    {
        wcout << L"line:[" << line << L"]" << endl;
    }
}

Also consider this for why use plain char UTF-8 streams.

You cannot treat ASCII string as a UNICODE string, since the characters they contain have different sizes. So you would have to do some kind of conversion to a temporary buffer and then use that piece of memory as an input buffer for your stream. This is what you're doing right now.

It should be obvious that if you have string, istream, and istringstream, therefore you also have wstring, wistream, and wistringstream.

Both istringstream and wistringstream are just specialization of the template class basic_istringstream for char and wchar respectively.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!