C++ How to write a string vector to file

In this post, we will discuss how to read/write string vector to a file in C++.

The simplest way to write a vector to a file is to store each element of the vector on a separate line.

void write(vector<string> v){
	ofstream file;
	file.open("text.txt");
	for(int i=0;i<v.size();++i){
		file<<v[i]<<endl;
	}
	file.close();
}

The above code writes each string of the vector to file text.txt. We insert “endl” at the end of each string to separate the strings from one another.

void read(vector<string> &v){
	ifstream file;
	file.open("text.txt");
	string line;
	while(getline(file, line)){
		v.push_back(line);
	}
	file.close();
}

The above code reads data from file text.txt line by line and push each line to vector v.

Complete Program

#include<iostream>
#include<vector>
#include<string>
#include<fstream>
using namespace std;

// write vector v to text.txt
void write(vector<string> v){
	ofstream file;
	file.open("text.txt");
	for(int i=0;i<v.size();++i){
		file<<v[i]<<endl;
	}
	file.close();
}

// read data from from text.txt and store it in vector v
void read(vector<string> &v){
	ifstream file;
	file.open("text.txt");
	string line;
	while(getline(file, line)){
		v.push_back(line);
	}
	file.close();
}

int main()
{
	vector<string> v  = {"My", "name", "is", "John", "Smith"};
	cout<<"Vector: ";
	for(int i=0;i<v.size();++i)
		cout<<v[i]<<" ";
	cout<<endl;
	
	//  writing v to file "text.txt"
	write(v);
	
	vector<string> temp;
	// reading vector from "text.txt" and storing data in temp
	read(temp);
	cout<<"Vector After Reading from File: ";
	for(int i=0;i<temp.size();++i)
		cout<<temp[i]<<" ";
	cout<<endl;
	
}

Output

text.txt content after write()

My
name
is
John
Smith

Note: The program writes a string vector to the file. If you want to store a vector of another datatype like an integer to the file, then you need to convert each element to string and then save it to the file. You can convert the string back to integer while reading from the file.

Leave a Comment

Your email address will not be published. Required fields are marked *