简体   繁体   中英

Converting a string of numbers into an int vector c++

Is there a simple way to convert a string of numbers separated by spaces into a vector of ints or something that I can easily convert into a vector?

I am creating an input operator (>>) to make a binary tree using values input from command line. And this is the main that goes with it

int main(int argc, char **argv)
{
stringstream stream;
stream << " 10" << " 11" << " 10" << " 2" << endl;
tree = new binary_tree();
stream >> *tree;
if (tree->inorder() != string("7 10 11")) //inorder() prints the tree in order
cout << "Test passed" << endl;
delete tree;

return 0;
}

The problem I am having is that while I can create and print the values that I need, I can't convert them and put them into a vector - for which I have a working defined method that creates a tree from the values.

std::istream& operator>>(std::istream &in, binary_tree &value)
{
vector<int> input_tree;
string readline;     
getline(in, readline);
cout << "(" << readline << ")" << endl; //prints correctly - (10 11 10 2)

    //where I need to insert insert values into vector

for(int i = 0; i < input_tree.size(); i++)
{
    insert(input_tree[i], value);    //inserts the values from a vector into a binary tree
}

return in;  
} 

I have tried looping through the string and using stoi() on each character but it always errored whenever the spaces were causing errors.

Thanks for any help and sorry if I've missed any important information out.

You can do this:

vector<int> vec((istream_iterator<int>(in)), istream_iterator<int>());

This will read integers from in and insert them into vec all in one line. It's a pretty canonical use of istream_iterator which is part of the standard library. Then you don't need to read each line and parse it yourself.

If you want to read more about how this works, see here: How does std::copy work with stream iterators

As for why there appear to be an extra pair of parentheses around the first argument, that's because of the "most vexing parse": https://en.wikipedia.org/wiki/Most_vexing_parse - just a silly quirk of C++ syntax.

A little easier to understand solution, I think (though less concise):

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;

int main() {
    string s= "4 5 6";
    stringstream ss(s);
    vector<int> v;

    int hlp;
    while(ss >> hlp)
    {
        v.push_back(hlp);
    }

    for(auto i: v)
        cout << i << '\n';
    return 0;
}

You can use a stringstream just as you could use cin .

http://ideone.com/Y6UfuW

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM