String stream in C ++ to parse a string of words and numbers

I have a line like this: '123plus43times7'

where the numbers are followed by words from the dictionary.

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

 StringStream >> number 

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

+5
source share
2 answers

You can insert a 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; } 
+3
source

here is 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; } 
+2
source

Source: https://habr.com/ru/post/1247390/


All Articles