get last word in string stream in C++
- User
get last word in string stream in C++
Assistant
Here is how you can get the last word in a string stream in C++ :
#include <iostream> #include <sstream> #include <string> std::string getLastWord(const std::string& str) { std::istringstream iss(str); std::string lastWord; std::string word; while (iss >> word) { lastWord = word; } return lastWord; } int main() { std::string str = "Hello World C++"; std::string last = getLastWord(str); std::cout << "Last word: " << last << std::endl; return 0; }The key steps are:
- Create a string stream (
istringstream) from the input string - Use a loop to extract words from the stream using the >> operator
- Save each extracted word to a variable, overwriting it each iteration
- After the loop, the last extracted word is the last word
The lastWord variable will contain the final word extracted from the stream, which is the last word in the original string.
- Create a string stream (
- User
get the last word of each line in a text file
Assistant
To get the last word of each line in a text file in C++, you can do:
#include <iostream> #include <fstream> #include <string> int main() { std::ifstream file("input.txt"); std::string line; while(getline(file, line)) { std::istringstream iss(line); std::string word; std::string lastWord; while(iss >> word) { lastWord = word; } std::cout << lastWord << std::endl; } file.close(); return 0; }The key steps are:
- Open the file using an ifstream
- Use a loop to read each line using getline()
- Create a string stream from the line
- Extract words from the stream and save the last one
- Print out the last word
This will print the last word of each line in the file. The same getLastWord() function from the previous example can also be used to encapsulate the logic of getting the last word from a string stream.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.