Boost: read_until "\ n" reads to ""

I am developing a tcp client using boost :: asio to handle incoming text that ends with "\ n". However, when I send text containing spaces, it returns all characters after the first space appears. I have already confirmed that the text I'm sending is complete.

This is my code:

boost::system::error_code error; boost::asio::streambuf buffer; boost::asio::read_until( *socket, buffer, "\n", error ); std::istream str(&buffer); std::string s; str >> s; 
+4
source share
2 answers

Use std::getline instead of >> , which stops reading when encountering spaces:

 std::istream str(&buffer); std::string s; std::getline(str, s); 
+11
source
  std::istream str(&buffer); std::string s; str >> s; 

If you check the contents of the buffer, you are mistaken. This would read std::string from a string that reads up to the first space character. What std::string operator<< does. If you keep doing >> s , you will get the rest of the information. Instead, you can use std::getline to retrieve all the content.

+3
source

All Articles