Search code examples
c++stringstream

What is the simplest way of retrieving the last element of a stringstream?


I am writing a Book class as a exercise from the C++ book I am reading. I want to store the last name of an Author for sorting all of the books.

So lets say the author is named: "Albert Ein Stein"

Then only the last name "Stein" should be separated and stored. The full name is stored in a string: std::string full_name = "Albert Ein Stein"

I thought converting the full name into a stringstream and somehow retrieving only the last element of the buffer would be a good solution. Something like this:

void get_last_name (const std::string& full_name)
{
    std::stringstream stream(full_name);
    auto it = stream.end() - 1;
    std::string last_name = *it;
}

But this is invalid syntax. What is a simple way to only retieve the last element of the string buffer?


Solution

  • I don't think you understand what streams are used for.

    You already have a std::string, just use its interface: rfind and substr.

    std::string get_last_name(const std::string& full_name)
    {
        auto last_word_pos = full_name.rfind(' ') + 1;
        return full_name.substr(last_word_pos);
    }
    

    Demo

    This assumes that the last name is always found after the last space, and that it does not itself contain a space. Also note that the "last element" of a string is just a character, not a word.