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?

Dani AI

Generated

Two practical, robust options that avoid the pitfalls of splitting on spaces:

  • 's istringstream approach works well when words and numbers are nicely separated by whitespace. It is simple and fine for many cases.
  • 's split-by-space example has logic problems (the find call never advances because no start index is passed, and the substr length is incorrect), and splitting on spaces breaks when punctuation or digits are attached to words.

A safer, compact approach is to extract digit runs with a regex and convert them. This handles multi-digit numbers, optional signs, and numbers embedded next to letters (adjust pattern if you only want isolated words):

#include <string>
#include <vector>
#include <regex>

std::string line = "The man is 67 years old and driving an Oldsmobile Rocket 88";
std::regex re("(-?[0-9]+)");   // match signed integers
std::vector<long long> numbers;

for (std::sregex_iterator it(line.begin(), line.end(), re), end; it != end; ++it) {
    numbers.push_back(std::stoll(it->str()));   // catch exceptions if you need to handle overflow
}

If you need maximum speed or want to avoid allocations/exceptions, scan the C string and use std::from_chars (C++17) to parse each numeric span:

#include <charconv>
#include <string>
#include <vector>

const std::string s = /* input */;
const char* p = s.c_str();
const char* e = p + s.size();
while (p < e) {
    if ((*p == '+' || *p == '-') && (p+1 < e) && isdigit(*(p+1))) { /* handle sign */ }
    if (isdigit(*p)) {
        const char* start = p++;
        while (p < e && isdigit(*p)) ++p;
        long long v;
        auto res = std::from_chars(start, p, v);
        if (res.ec == std::errc()) numbers.push_back(v);
    } else ++p;
}

Notes and tips:

  • Use [0-9]+ rather than \d for portability in std::regex.
  • std::regex in some old standard-library versions had bugs; if it misbehaves, fallback to manual scanning or Boost.Regex.
  • Decide how to handle signs, decimals, overflow, and numbers stuck to letters; adjust the regex or scanner accordingly.

See std::regex and std::from_chars for details: https://en.cppreference.com/w/cpp/regex and https://en.cppreference.com/w/cpp/utility/from_chars.

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.