reading integers from text file

I received some helpful information on an earlier question. But as I started investigating the suggestions made, I realized that my question requires things that are too advanced for me just yet. So I have a simpler question.

If I have a text file with many lines of only integers, how can I stream this into a new program as an array (or vector, I'm not really sure which is better) of integers? (I have been able to stream them in and display them on the screen, but they're just strings, and I can't manipulate them as integers)

Each line of text in the file looks something like this:
0 1 2 3 4 5 6 7 8 9 10 11
2 3 1 4 7 6 5 9 10 11 8 0
5 4 1 2 7 8 6 9 3 10 0 11
etc. (exactly 12 integers per line)

I want to stream them in so that each line is a new array, so I can add the 1st element of array 1 to the 3rd element of array 5, or whatever...

I've seen things online about using stringstream, but I haven't been able to understand how. I'm going to keep looking...

Thanks for any help!
Last edited on
If you have a single string containing a number, you can use stringstream to convert it into an integer:
1
2
3
4
5
6
#include <sstream> //stringstream library
...
string str="123"; //string containing a number
int number;
stringstream myStream(str); //create the stringstream
myStream>>number; //convert the string to an integer 


You can use the memberfunctions find() and substr() to find the different numbers per line and seperate them into single strings:
http://www.cplusplus.com/reference/string/string/find.html
http://www.cplusplus.com/reference/string/string/substr.html
Topic archived. No new replies allowed.