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?

Recommended Answers

All 2 Replies

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.

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];
commented: It's pi +11
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.