From a Vector of string to an array of ints

Started by
5 comments, last by Zahlman 18 years, 4 months ago
I have a tile map with comma delimited tile codes in it. Ive read the file, broke it down into its correct numbers i.e 123,44,67 into -> 123 44 67 And stored them in vector i want to take them out of the vector and bung them in an array of ints, but whats the best way to cast them to ints? i tried a stringstream in a for(0 -> vector.size) loop but it seemed to just spit out the first number it converted over and over. What the best way of going about this?
Advertisement
Try boost::lexical_cast, or make sure that you clear() the flags on the stringstream after every extraction.
Quote:Original post by SiCrane
.... or make sure that you clear() the flags on the stringstream after every extraction.

2 things....
1)Thanks.
&
2)Whoops, whats a silly thing for me to overlook.
Try reading them directly into an vector of ints (and then creating an array from that without any "casting", if you *really* need to make such an array).

vector<int> result;int current;char comma;while(file >> current) {   result.push_back(current);   file >> comma;  // optionally check if it actually was a comma.}


Better yet, separate the values in your file with whitespace instead of commas so that you don't have to worry about that part of the parsing.
Zahlman, so if i whitespace delimit can I read directly into a an int?
How is this done?
At the moment im doing:

 while ((getline(ReadMap,ReadIn,',')) != NULL)       {                LevelList.push_back(ReadIn);                        }


To read into a string(ReadIn) but if i could just read the delimited numbers into an int it would save time and coding.

Cheers.
Let's assume you have a file that has nothing but integers in it. You can read it into a vector like so:
std::ifstream ifs("filename");std::istream_iterator begin(ifs);std::istream_iterator end;std::vector<int> int_vector(begin, end);

This will be equivalent to using operator>> to read in every int. Of course this isn't appropriate if your file has any structure further than just being a list of ints.
Quote:Original post by JDUK
Zahlman, so if i whitespace delimit can I read directly into a an int?
How is this done?


For a single int, with the usual stream extraction operator:

(stream object) >> (int variable);

This topic is closed to new replies.

Advertisement