What's the best way to edit words in an input sentence?

Let's say the input is "My name is Michael, and I am 36 years old."
I'm using getline(cin, str) and then looking for spaces to be new indices to create substrings. Is there an easier way?
By edit words, I mean separate the sentence into words without spaces and then doing things with the words. The problem I have right now is that I have no way of getting the last word.
Last edited on
If all you want is the last word you could use the std::string.find_last_of() function to find the last whitespace character, then use the substr() function to extract that word. You could also use a stringstream and extract each word from the string using the extraction operator.

Since that your input is cin, which is a stream buffer, you can use the >> operator directly to extract only until space char.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
    string str;
    vector<string> splitted;
    do {
        cin >> str;
        splitted.push_back(str);
    } while(cin.peek() != '\n');
    cin.ignore(1, '\n');
    for(string s : splitted) {
        cout << s << endl;
    }
    return 0;
}


If you want to split a char * that is not in cin you'll have to use the sstream library to simulate a stream buffer.
Topic archived. No new replies allowed.