get last word in string stream in C++
- User
get last word in string stream in C++
- Assistant
In order to get the last word in a string in C++, you can use the
std::istringstreamclass from the<sstream>library along with thestd::stringclass from the<string>library.Here is a simple example:
cpp#include <sstream> #include <string> std::string getLastWord(std::string str) { std::istringstream iss(str); std::string word; std::string lastWord; while (iss >> word) { lastWord = word; } return lastWord; }In this function, an
std::istringstreamobjectissis created from the input stringstr. Then, the operator is used within a while loop to extract words from one by one. Every word extracted is stored in the string and also copied to . When the loop finishes, contains the last word extracted from , which is the last word of the input string.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.