Reading content from a string stream

I tested how to read data from std::streamstring , but I am mistaken, could anyone indicate what the problem is? and give the right way to read it?

My test code is:

 #include <iostream> #include <string> #include <sstream> #define BUFFER_SIZE 16 int main(int argc, char ** argv) { std::stringstream ss; ss << "Un texto con datos de ejemplo para probar la extacción de un stream"; std::cout << "Stream contents: '" << ss.str() << "'" << std::endl; char buffer[BUFFER_SIZE] = {0}; std::streamsize read = 0; do { read = ss.readsome(buffer, BUFFER_SIZE - 1); std::cout << "Read: " << ss.gcount() << std::endl; std::cout << buffer << std::endl; std::cout << "---" << std::endl; std::fill(buffer, buffer + BUFFER_SIZE, 0); } while ( read > 0 ); return 0; } 

And I get the output:

 Stream contents: 'Un texto con datos de ejemplo para probar la extacci¾n de un stream' Read: 15 Un texto con da --- Read: 15 tos de ejemplo --- Read: 15 para probar la --- Read: 15 extacci¾n de un --- Read: 5 stre --- Read: 0 --- 

As you can see, the last read operation reads only 5 characters, leaving the last two "s", although it should have read it. Am I missing somtehing?

+5
source share
1 answer

Actually, readsome only reads the available characters and that it depends on the platform, so it’s quite possible to return 0, while there are still characters in the stream, and a subsequent call can probably return the missing characters. To get all the data available, I'd rather use read in conjunction with gcount to get the number of characters you are reading.

 do { ss.read(buffer, BUFFER_SIZE - 1); read=ss.gcount(); std::cout << "Read: " << ss.gcount() << std::endl; std::cout << buffer << std::endl; std::cout << "---" << std::endl; std::fill(buffer, buffer + BUFFER_SIZE, 0); } while ( read > 0 ); 

For clarification only:
Although I believe that the behavior you observe is allowed by the standard, I don’t understand why the implementation should behave when the input stream is based on a string literal (they are not familiar with the details of the stream implementation). What could you check if read really matches rdbuf()->in_avail() , and if it doesn't, it could be a compiler error.

+3
source

All Articles