Reading a sentence and saving parts of the sentence into differnet variables

Hi folks,

I am starting in C++ and I have a the following problem:

cout<<"enter 123HDog and cat W346 edf gefh are good"<<endl

1*Save 123 into x
2*Save Dog and cat into str
3*Save 346 into y
4*Save are good into line

My program read 123 and converted to integer, however it is unable to keep reading and assigning the remaining characters to the specific containers.

I tried functions, classes. I am totally lost and I need help with the logic please.

Thank you.[/b]

A few questions:
1. Why is "enter" not saved?
2. Why is "edf gefh" not saved?

If the answer is: "I am only looking for specific words", then this is easy!

Make sure that the entire contents of your line are in a std::string container.
1
2
std::string MyLine;
MyLine = "enter 123HDog and cat W346 edf gefh are good";


Make a dictionary of the words you want to search:
1
2
3
4
5
std::vector<std::string> Dictionary;
Dictionary.push_back( std::string("Dog") );
Dictionary.push_back( std::string("car") );
Dictionary.push_back( std::string("are") );
Dictionary.push_back( std::string("good") );


Then search for each word in the dictionary and remove it from the string if found. We're saving it to our own std::string.
1
2
3
4
5
6
7
8
9
10
11
12
std::vector<std::string> Tokens;

// for each word in our dictionary...
for (std::vector<std::string>::iterator it = Dictionary.begin(); it != Dictionary.end(); ++it)
{
    std::size_t found = MyLine.find(*it); // Search for the token
    if (found != std::string::npos) // Was it found?
    {
        MyLine.erase(found, it->size()); // Take it out of our word
        Tokens.push_back(*it); // Put it into a vector of words
    }
}


JuanCamaney wrote:
I tried functions, classes.

This is funny. In effect you are saying, "I tried C++".
It's not clear what are the rules used.
Take this input string: "enter 123HDog and cat W346 edf gefh are good"
Broken into numeric and non-numeric parts, it would look like this:
1. "enter"
2. 123
3. "HDog and cat W"
4. 346
5. " edf gefh are good"

So the question at this stage is a clarification of the requirements please, how to determine which characters to put into the string.
What happened to "enter", "H", "W", " edf gefh "? On what basis are these characters or words discarded?

And please don't post the same question multiple times.
Last edited on
Topic archived. No new replies allowed.