String stream to vector <int>
I am wondering what is the best way to write from std::stringstream to vector<int> .
Here is an example of what is in stringstream : "31 #00 532 53 803 33 534 23 37"
Here is what I have:
int buffer = 0; vector<int> analogueReadings; stringstream output; while(output >> buffer) analogueReadings.push_back(buffer); Be that as it may, he reads the first, and then gets #00 and returns 0 because it is not a number.
Ideally, I want it to get # , and then just skip all characters to the next space. Is this possible with flags or something?
Thanks.
#include <iostream> #include <sstream> #include <vector> int main ( int, char ** ) { std::istringstream reader("31 #00 532 53 803 33 534 23 37"); std::vector<int> numbers; do { // read as many numbers as possible. for (int number; reader >> number;) { numbers.push_back(number); } // consume and discard token from stream. if (reader.fail()) { reader.clear(); std::string token; reader >> token; } } while (!reader.eof()); for (std::size_t i=0; i < numbers.size(); ++i) { std::cout << numbers[i] << std::endl; } } You need to check if you have a number or not. use the answer from here:
How to determine if a string is a number with C ++?
#include <iostream> #include <sstream> #include <vector> using namespace std; bool is_number(const std::string& s){ std::string::const_iterator it = s.begin(); while (it != s.end() && std::isdigit(*it)) ++it; return !s.empty() && it == s.end(); } int main () { vector<int> analogueReadings; std::istringstream output("31 #00 532 04hello 099 53 803 33 534 23 37"); std::string tmpbuff; while(output >> tmpbuff){ if (is_number(tmpbuff)){ int num; stringstream(tmpbuff)>>num; analogueReadings.push_back(num); } } } the result is 31 532 99 53 803 33 534 23 37
In addition, important disadvantages of using lexical reductions similar to those described here are described here: How to parse a string in int in C ++? where the alternative tringstream(tmpbuff)>>num provided.
For example, 04hello becomes 4, and 7.4e55 becomes 7. There are also terrible problems with the downstream and downstream. Andre Caron's net decision converts
25 10000000000 77 0 0 in
25 0 0 on my system. Please note that 77 is missing!
No loop:
#include <iostream> #include <vector> #include <iterator> #include <algorithm> #include <sstream> using namespace std; class IntegerFiller { vector<int> &m_vec; public: IntegerFiller(vector<int> &vec): m_vec(vec) {} void operator()(const std::string &str) { stringstream ss(str); int n; ss >> n; if ( !ss.fail() ) m_vec.push_back(n); } }; int main() { vector<int> numbers; IntegerFiller filler(numbers); for_each(istream_iterator<string>(cin), istream_iterator<string>(), filler); copy(numbers.begin(), numbers.end(), ostream_iterator<int>(cout, " ")); return 0; }