6

I have string like this: '123plus43times7'

where numbers are followed by words from a dictionary.

I understand that I can extract int/numbers by using the >> operator:

StringStream >> number

I can get the number. However, the Stream still has the number in it. How do I remove the number when the length of number is unknown or should I find out length of number and then use str.substr() to create a new String Stream ? Any other better method for doing it using C++ STL String and SStream would be really appreciated.

2
  • 1
    It would seem a lot simpler to just read the whole string into a std::string and then iterate over the characters to separate it into blocks of consecutive digits and blocks of letters. When you have the blocks separated, then you can convert the sequences of digits into integers via std::atoi(). Commented Apr 18, 2016 at 23:24
  • @DanMašek is correct. Once you get a number, you grab a string and a >> to a string will only stop on whitespace. It will grab your letters, your numbers and everything else that gets in it's way. Commented Apr 18, 2016 at 23:28

2 Answers 2

6

You can insert blank space between text and numbers and then use std::stringstream

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

int main() 
{
    std::string s = "123plus43times7";
    for (size_t i = 0; i < (s.size() -1 ); i++)
    {
        if (std::isalpha(s[i]) != std::isalpha(s[i + 1]))
        {
            i++;
            s.insert(i, " ");
        }
    }
    std::stringstream ss(s);
    while (ss >> s)
        std::cout << s << "\n";
    return 0;
}
Sign up to request clarification or add additional context in comments.

2 Comments

What does while (ss >> s) do? It seems to overwrite the original string s. Does that mean ss keeps a copy of (the original) s?
This will overwrite s each time. ss is similar to a file stream, its content doesn't change, but it does move to the next file position after each operation. See the result here: ideone.com/qvJvMV
2

here's one way to do it

string as = "123plus43times7";

    for (int i = 0; i < as.length(); ++i)
    {
        if (isalpha(as[i]))
            as[i] = ' ';
    }

    stringstream ss(as);
    int anum;

    while (ss >> anum)
    {
        cout << "\n" << anum;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.