How to convert vector to a stringstream

Hello,

I'm writing 2 programs, first program does the following tasks :

1. Has a vector of integers
2. convert it into string
3. write it in a file

The code of the first program :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
vector<int> v = {10, 200, 3000, 40000};
int i;
stringstream sw;
string stringword;

cout << "Original vector = ";
for (i=0;i<v.size();i++) 
{
  cout << v.at(i) << " " ;
}
cout << endl;

for (i=0;i<v.size();i++) 
{
  sw << v[i];
}
stringword = sw.str();
cout << "Vector in array of string : "<< stringword << endl;
    
cout << "Writing to File ..... " << endl;
	
ofstream myfile;
myfile.open ("writtentext");
myfile << stringword;
myfile.close();


Output from the first program :
1
2
3
Original vector : 10 200 3000 40000
Vector in string : 10200300040000
Writing to File ..... 


Second program does the following tasks :

1. read the file
2. convert the array of string back into original vector

So far, the code of the second program :

1
2
3
4
5
6
string stringword;
	
ifstream myfile;
myfile.open ("writtentext");
getline (myfile,stringword);
cout << "Read From File = " << stringword << endl;


I have not finished the second program because I have a question :

How to convert the string from the first program back to the original vector?

Intended result for the second program is :

1
2
Read from File = 10200300040000
Original Vector = 10 200 3000 40000


I appreciate any helps.
i think it would be easier for you to manipulate your data.
if you can seperate the data out with a "," or some other delimiter before you write it to file. if your digits vary in length.

otherwise just read the string and seperate it out manually.
you can write a for loop to shorten the example code below.

1
2
3
4
5
stringstream out;

out << string[0] << string[1] << " ";
      << string[2] << string[3] << string[4] << " ";


if your patter is exactly 2 , 3 , 4 , 5. just read that many characters.
Topic archived. No new replies allowed.