Reading a specific number of characters from C++ stream into std::string

痴心易碎 提交于 2021-01-27 04:56:17

问题


I'm pretty familiar with most of C++ but one area I've avoided has been IO streams, mainly because I've been using it on embedded systems where they're not appropriate. Recently I've had to become familiar with them, however, and I'm struggling to figure out something that I feel should be simple.

What I'm looking for a relatively efficient way to read a fixed number of characters from a C++ stream into a std::string. I could easily read into a temporary char array with the read() method and convert that into a std::string, but that's fairly ugly and involves a wasteful copy. I could also read the whole of a stream into a string with something like this:

std::string getFile(std::fstream &inFile)
{
    std::stringstream buffer;
    buffer << inFile.rdbuf();
    return buffer.str();
}

... But unbounded reads into memory are generally a poor idea, so I'd really like to access the file one block at a time, say 4K or so. I could also read character at a time, but that just feels both uglier and less efficient than reading into a temporary char array.

So, is there a simple way to get a std::string directly from a stream which contains the next N characters from the stream? It may well be that there is simply no way to do this, but it seems strange to me that such a thing would be missing so I felt I must be missing something glaringly obvious.

By the way, I'm quite familiar with the C file IO APIs and I'm not looking for a solution involving them. I could knock something up with read() and write(), but the code I'm working with makes heavy use of streams and I think it's good practice to keep my code additions in a consistent style.


回答1:


You are on the right track. :)

mystring.resize( 20 );
stream.read( &mystring[0], 20 );

Edit:

In C++11. this is well-defined and safe. Unlike data() and c_str(), std::string::operator[] provides a mutable reference to the underlying data.

In C++03, It is safe in a practical sense, but the definition of std::string was too weak to guarantee this safety. C++03 allowed string data to be non-contiguous, but I don't believe any available implementation ever took advantage of that.



来源:https://stackoverflow.com/questions/15883553/reading-a-specific-number-of-characters-from-c-stream-into-stdstring

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