I'm writing 2 programs, the first program has an array of integers
vector<int> v = {10, 200, 3000, 40000};
Then it converts the vector into string
int i;
stringstream sw;
string stringword;
for (i=0;i<v.size();i++)
{
sw << v[i] << ',';
}
stringword = sw.str();
cout << "Vector in string : "<< stringword << endl;
And then write it in a file
ofstream myfile;
myfile.open ("writtentext");
myfile << stringword;
myfile.close();
The output :
Vector in string : 10,200,3000,40000
The second program will read the file, convert the string back to integer, and then push it back to vector.
The code :
string stringword;
ifstream myfile;
myfile.open ("writtentext");
getline (myfile,stringword);
cout << "Read From File = " << stringword << endl;
cout << "Convert back to vector = " ;
for (int i=0;i<stringword.length();i++)
{
if (stringword.find(','))
{
int value;
istringstream (stringword) >> value;
v.push_back(value);
stringword.erase(0, stringword.find(','));
}
}
for (int j=0;j<v.size();j++)
{
cout << v.at(j) << " " ;
}
The problem is, it can only convert and push back the first element, the rest is erased. Here is the output :
Read From File = 10,200,3000,40000,
Convert back to vector = 10
What did I do wrong? Thanks