# From a Vector of string to an array of ints

## Recommended Posts

JDUK    100
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?

##### Share on other sites
SiCrane    11839
Try boost::lexical_cast, or make sure that you clear() the flags on the stringstream after every extraction.

##### Share on other sites
JDUK    100
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.

##### Share on other sites
Zahlman    1682
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.

##### Share on other sites
JDUK    100
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.

##### Share on other sites
SiCrane    11839
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.

##### Share on other sites
Zahlman    1682
Quote:
 Original post by JDUKZahlman, 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);