0

Hi, I've used getline and pushed back a text row into a vector.
The vector is of string type and I want to sort out the numbers and store it elsewhere.

in my vector: The man is 67 years old and driving an Oldsmobile Rocket 88

I want to sort out 67 and 88.

I've seen examples using char but i really want to sort out numbers from the text larger than one digit. Any ideas?

3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by Clinton Portis
0

1. Create istringstream (f.e. istringstream my_stream ) from string stored in vector.
2. Create a while loop (until you reach eof of the stream)
3. Use operator >> and try to save to int variable (f.e. int my_int ). my_stream>>my_int; 4. Check state of the stream. If it returns false, means that it wasn't a number. Reset the state of the stream (clear()) and use operator >> for string variable (f.e. string my_string ). my_stream>>my_string 5. If checking stream state returns true, means that You read integer.
6. Repeat.

Edited by pecet: n/a

1

try this string parsing algorithm to split your line up into individual strings:

#include<string>
#include<vector>

int prev = 0;
int curr = 0;
string temp;
string line = "The man is 67 years old and driving an Oldsmobile Rocket 88";
vector<string> vstring;

do{
     prev = curr;
     curr = line.find(' ');

     if(curr == string::npos)
          temp = line.substr(prev);
     else     
          temp = line.substr(prev, curr-1);

     vstring.push_back(temp);
     
  }while(curr != string::npos);

Now you can just test elements of the vstring vector to get what you want:

string word;

cout << "Enter word to find: ";
cin >> word;

for(int i=0, size=vstring.size(); i<=size; i++)
{
     if(word == vstring[i])
          break;
}

if(i == size)
     cout << "word not found";

else
     cout << word << " found at element " vstring[i];

Edited by Clinton Portis: wicked clown.

Votes + Comments
It's pi
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.