I need to take in a sentence and break it up based on the individual words.

I've been googling for probably 30+ minutes to 60 ish and I feel it's time I get some help on this one..

Ideally, there should be a way to break up a string possible using white spaces as a delimiter that isn't going to limit the length of the sentence (like a character array would) while allowing me to send the individual words to a pre-existing method I created which can change individual words into pig latin. I just don't know how I'd go about doing this..

(Sorry if I am breaking any rules here, although it is the same project, it is a different issue I figured this would be a better way to go about it)

Recommended Answers

All 5 Replies

The >> operator is whitespace delimited by default when used with any kind of stream; including cin, fstream and stringstream; so you can use that to your advantage to turn a stringstream into a simple tokeniser

e.g.

#include <string>
#include <sstream>
#include <iostream>

...

std::istringstream hello("the cat sat   on \n\t the mat");
std::string fred;
while( hello >> fred )
{
    std::cout << fred << std::endl;
}

This is also doable for any other type of delimiter, though you need to fiddle a little bit if using something else such as commas etc (std::getline also works with stringstreams).

The >> operator is whitespace delimited by default when used with any kind of stream; including cin, fstream and stringstream; so you can use that to your advantage to turn a stringstream into a simple tokeniser

e.g.

#include <string>
#include <sstream>
#include <iostream>

...

std::istringstream hello("the cat sat   on \n\t the mat");
std::string fred;
while( hello >> fred )
{
    std::cout << fred << std::endl;
}

This is also doable for any other type of delimiter, though you need to fiddle a little bit if using something else such as commas etc (std::getline also works with stringstreams).

So, I can cin something like?

std::istringstream hello("");
getline(cin,hello);

or is that doing it completely wrong?

getline reads into a string from a stream; it's not designed to swap data between two streams. But you can do this:

std::string line;
std::getline(std::cin,line);
std::istringstream hello(line);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.