Search code examples
c++stringvectorfwritefread

How to convert vector to string and convert back to vector


----------------- EDIT -----------------------

Based on juanchopanza's comment : I edit the title

Based on jrok's comment : I'm using ofstream to write, and ifstream to read.

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

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

The code of the first program :

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;

ofstream myfile;
myfile.open ("writtentext");
myfile << stringword;
myfile.close();

The output of the first program :

Original vector : 10 200 3000 40000
Vector in string : 10200300040000
Writing to File ..... 

second program will do the following tasks :

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

----------------- EDIT -----------------------

Now the writing and reading is fine, thanks to Shark and Jrok,I am using a comma as a separator. The output of first program :

Vector in string : 10,200,3000,40000,

Then I wrote the rest of 2nd program :

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();i++) 
{
    cout << v.at(i) << " " ;
}

But 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


Solution

  • The easiest thing would be to insert a space character as a separator when you're writing, as that's the default separator for operator>>

    sw << v[i] << ' ';
    

    Now you can read back into an int variable directly, formatted stream input will do the conversion for you automatically. Use vector's push_back method to add values to it as you go.