2

"Working in C++"

I have a UnicodeString that contains some comma seperated integer values e.g: UnicodeString usCSVs = "3,4,5,6";

I need to store these values in std::vector < int>. What would be the best possible way of achieving the above functionality.

Regards, JS

J Stephan
  • 93
  • 8

2 Answers2

4

You can use std::istream_iterator to parse the string. Before that you need to replace all delimiters to spaces.

 std::vector<int> myarr;
 std::string int_str = "3,4,5,6";
 std::replace( int_str.begin(), int_str.end(), ',', ' ' );
 std::stringstream in( int_str );
 std::copy( std::istream_iterator<int>(in), std::istream_iterator<int>(), std::back_inserter( myarr ) );

For UNICODE version it will look like:

 std::wstring int_str = L"3,4,5,6";
 std::replace( int_str.begin(), int_str.end(), L',', L' ' );
 std::wstringstream in( int_str );
 std::copy( std::istream_iterator<int, wchar_t>(in), std::istream_iterator<int, wchar_t>(), std::back_inserter( myarr ) );
Kirill V. Lyadvinsky
  • 97,037
  • 24
  • 136
  • 212
  • niiice, +1 from me, namesake xD – Kiril Kirov Dec 22 '10 at 08:21
  • Than a lot, i am looking for such sort of thing. But i am new to C++ so its difficult for me to understand whole logic. So could you plz answer the following question: Do we really need to replace ',' with ' '? If yes, then why? Could you please elaborate the last statement in code? Could you recommend me some good book or web URL from where i would learn the string manipulations like you code – J Stephan Dec 22 '10 at 09:06
  • Besides, you can write your own `istream_iterator` which will works with `,`, but using `replace` is simpler. – Kirill V. Lyadvinsky Dec 22 '10 at 09:12
  • A good set of C++ Books you can find [here](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Kirill V. Lyadvinsky Dec 22 '10 at 09:14
  • Thnx, plz tell me one more thing what is the meaning of first two arguments in the copy functions, usally it denotes the start and end of container, but how first two argumnets work in our case? std::copy( std::istream_iterator(in), std::istream_iterator(), std::back_inserter( myarr ) ); – J Stephan Dec 22 '10 at 11:53
  • These arguments are iterators. They are point to the begin and the end of the stream. – Kirill V. Lyadvinsky Dec 22 '10 at 12:07
1

Parse the string, first of all. You could iterate through it using std::string::find, that returns a position. You should find the delimiter - ','. Then, get the substring, closed between two commas and use std::stringstream. Done

Kiril Kirov
  • 37,467
  • 22
  • 115
  • 187